【问题标题】:React Native Functional Component - ref "No overload matches this call."React Native 功能组件 - 参考“没有重载匹配此调用。”
【发布时间】:2021-11-27 02:38:01
【问题描述】:

我是 JavaScript/TypeScript 和 React Native 的新手——尤其是钩子。但是我有这个功能组件,我正在尝试弄清楚如何将 refs 与组件一起使用。我不确定我在这里是否正确使用了 ref(我想我可能需要将它放在不同的上下文中,但这不是我目前主要关心的问题)。我想弄清楚的是如何在 React Native 功能组件中使用 refs/hooks。

这是我现在得到的:

export default function BasicView(
  props: BasicViewProps
): JSX.Element {
  const basicRef = React.createRef();
  return (
    <View
      // Visual Studio Code error on ref: "No overload matches this call."
      // Note: I've also tried basicRef.current
      ref={basicRef}
      style={{
        maxHeight: 100,
        width: 100,
      }}
    >
      <Text>
        {props.txt}
      </Text>
    </View>
  );
}

当我玩弄这个时,我注意到这并没有给我一个错误:

   ...
      // This works, though I'm not sure if it's useful at all if it's not a variable.
      ref={React.createRef()}
   ...

在 React Native 功能组件中使用 refs 和 createRef 的适当方式是什么?我在互联网上进行了很多搜索,很多人似乎在使用 refs 方面取得了成功,但我在所见过的任何方法上都没有取得任何成功。那么我在这里做错了什么?

【问题讨论】:

    标签: typescript react-native


    【解决方案1】:

    在函数组件中,您需要使用useRef() 挂钩,而不是createRef() 函数。这样,每次组件渲染时,您都会得到相同的RefObject

    你可以这样使用它:

    const BasicView: React.FC<BasicViewProps> = (props) => {
        // We need to tell TypeScript that this is a reference to a View,
        // as a RefObject can hold anything. The actual type of our
        // basicRef constant is RefObject<View | null>.
        const basicRef = React.useRef<View>(null);
        
        return (
            <View
                ref={basicRef}
                ...
            />
        );
    };
    

    【讨论】:

    • 这太好了,谢谢!将RefObject 键入为View 绝对是我在尝试使用useRef() 时缺少的东西。但看起来我终于得到了一些有用的东西。再次感谢。
    猜你喜欢
    • 2021-11-03
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多