【问题标题】:React native error on ref scrollview, but working在参考滚动视图上反应本机错误,但工作
【发布时间】:2020-11-18 10:21:57
【问题描述】:

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

const scrollViewRef = useRef();


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

但我收到了这些错误:

第一个是:

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'.

有什么建议吗?

【问题讨论】:

    标签: javascript reactjs typescript react-native syntax-error


    【解决方案1】:

    您需要将 type 传递给 useRef 并且 scrollViewRef current 可以为 null 所以只需创建一个 if 或 use ?运算符。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-21
      • 2019-10-25
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 2020-04-19
      • 2023-01-03
      • 2021-08-12
      相关资源
      最近更新 更多