代码之家  ›  专栏  ›  技术社区  ›  Ilja

在react native with typescript中使用createRef?

  •  2
  • Ilja  · 技术社区  · 7 年前

    我在想我该怎么用 React.createRef() 在react native with typescript中,以下代码抛出错误

     // ...
    
      circleRef = React.createRef();
    
      componentDidMount() {
        this.circleRef.current.setNativeProps({
          someProperty: someValue
        });
      }
    
      // ...
    

    this.circleRef.current.setNativeprops

    [ts]对象可能为“null”(财产) React.reObject<{}>。当前:{}|空

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

    有什么想法吗?

    1 回复  |  直到 7 年前
        1
  •  7
  •   Matei Radu Ciaran George    7 年前

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

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

    第二个问题通过传递要为其创建引用的节点元素的类名来解决。例如,如果引用的元素是 <Text> ,然后执行:

    circleRef = React.createRef<Text>();
    

    circleRef setNativeProps 将存在 当且仅当引用的组件由本机视图直接支持时 :

    方法 current Direct Manipulation - React Native documentation

        2
  •  4
  •   jefelewis    5 年前

    您可以向React Native Ref添加Typescript类型,如下所示:

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