在参考滚动视图上反应本机错误,但可以工作

sam*_*uel 3 javascript syntax-error typescript reactjs react-native

我需要滚动到平面列表的底部,所以我使用:

const scrollViewRef = useRef();


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

Run Code Online (Sandbox Code Playgroud)

但我得到了这些错误:

在此输入图像描述

第一个是:

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<...>'
Run Code Online (Sandbox Code Playgroud)

第二个是:

Object is possibly 'undefined'.
Run Code Online (Sandbox Code Playgroud)

有什么建议么?

ant*_*ñoz 8

您需要将类型传递给useRef,而scrollViewRef当前可以为空,所以只需创建一个if或use?操作员。

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


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