【问题标题】:Using createRef in react-native with typescript?在带有 typescript 的 react-native 中使用 createRef?
【发布时间】:2019-03-17 11:10:34
【问题描述】:

我正在尝试弄清楚我需要如何使用React.createRef() 与 typescript 进行本机反应,因为以下代码会引发错误

 // ...

  circleRef = React.createRef();

  componentDidMount() {
    this.circleRef.current.setNativeProps({
      someProperty: someValue
    });
  }

  // ...

当前为this.circleRef.current.setNativeprops 引发以下错误

[ts] 对象可能为“空”。 (财产) React.RefObject.current: {} |空

和

[ts] 类型“{}”上不存在属性“setNativeProps”。任何

有什么想法吗?

【问题讨论】:

    标签: reactjs typescript react-native react-ref


    【解决方案1】:

    第一个问题可以在继续执行您的逻辑之前通过空检查来解决,因为React.createRef() 也可以返回null:

    componentDidMount() {
      if(this.circleRef !== null && this.circleRef.current !== null) {
        this.circleRef.current.setNativeProps({
          someProperty: someValue
        });
      }
    }
    

    第二个是通过传递要为其创建引用的 Node 元素的类名来解决的。例如,如果您引用的元素是 <Text>,则执行以下操作:

    circleRef = React.createRef<Text>();
    

    这样,circleRef 将被正确键入并且setNativeProps 将存在当且仅当引用的组件直接由本机视图支持时:

    [current] 的方法在 React Native 提供的大多数默认组件上都可用。但是请注意,它们在不直接由本机视图支持的复合组件上不可用。这通常包括您在自己的应用程序中定义的大多数组件。 - Direct Manipulation - React Native documentation

    【讨论】:

    • 那么,有没有办法在createRef中使用自定义组件的类型呢?喜欢:const customCompRef = React.createRef&lt;CustomComponentType&gt;()
    【解决方案2】:

    您可以像这样将 Typescript 类型添加到 React Native Ref:

    const textInputRef: React.RefObject<TextInput> = React.createRef();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-04
      • 2021-11-22
      • 2017-04-27
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      相关资源
      最近更新 更多