在带有打字稿的 react-native 中使用 createRef?

Ilj*_*lja 7 typescript reactjs react-native react-ref

我试图弄清楚我需要如何使用React.createRef()打字稿来响应本机,因为以下代码会引发错误

 // ...

  circleRef = React.createRef();

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

  // ...
Run Code Online (Sandbox Code Playgroud)

目前抛出以下错误 this.circleRef.current.setNativeprops

[ts] 对象可能为“空”。(属性) React.RefObject<{}>.current: {} | 空值

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

有任何想法吗?

jef*_*wis 10

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

const textInputRef: React.RefObject<TextInput> = React.createRef();
Run Code Online (Sandbox Code Playgroud)


Mat*_*adu 7

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

componentDidMount() {
  if(this.circleRef !== null && this.circleRef.current !== null) {
    this.circleRef.current.setNativeProps({
      someProperty: someValue
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

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

circleRef = React.createRef<Text>();
Run Code Online (Sandbox Code Playgroud)

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

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