React Native错误:ref scrollview,但工作

3
我需要滚动到FlatList的底部,所以我使用以下代码:
const scrollViewRef = useRef();


//my scroll view
<ScrollView
    ref={scrollViewRef}
    onContentSizeChange={() => {
        scrollViewRef.current.scrollToEnd({ animated: true });
    }}

但我遇到了以下错误:

enter image description here

第一个错误是:

No overload matches this call.
  Overload 1 of 2, '(props: Readonly<ScrollViewProps>): ScrollView', gave the following error.
    Type 'MutableRefObject<undefined>' is not assignable to type 'string | ((instance: ScrollView | null) => void) | RefObject<ScrollView> | null | undefined'.
      Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<ScrollView>'.
        Types of property 'current' are incompatible.
          Type 'undefined' is not assignable to type 'ScrollView | null'.
  Overload 2 of 2, '(props: ScrollViewProps, context?: any): ScrollView', gave the following error.
    Type 'MutableRefObject<undefined>' is not assignable to type 'string | ((instance: ScrollView | null) => void) | RefObject<ScrollView> | null | undefined'.
      Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<ScrollView>'.ts(2769)
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<ScrollView> & Readonly<ScrollViewProps> & Readonly<...>'
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<ScrollView> & Readonly<ScrollViewProps> & Readonly<...>'

第二个是:
Object is possibly 'undefined'.

有什么建议吗?

1个回答

7

你需要给useRef传递type参数,而scrollViewRef的current可能为空,因此需要使用if语句或者使用问号操作符。

const scrollViewRef = useRef<ScrollView|null>(null);


//my scroll view
<ScrollView
    ref={scrollViewRef}
    onContentSizeChange={() => {
        scrollViewRef?.current?.scrollToEnd({ animated: true });
    }}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接