在 typescript 的 react-native 中使用 createRef?

Using createRef in react-native with typescript?

我正在尝试弄清楚我需要如何使用 React.createRef() 来对原生的 typescript 进行反应,因为以下代码会抛出错误

 // ...

  circleRef = React.createRef();

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

  // ...

当前为 this.circleRef.current.setNativeprops

抛出以下错误

[ts] Object is possibly 'null'. (property) React.RefObject<{}>.current: {} | null

[ts] Property 'setNativeProps' does not exist on type '{}'. any

有什么想法吗?

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

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

第二个是通过传递要为其创建引用的节点元素的 class 名称来解决的。例如,如果您引用的元素是 <Text>,则执行:

circleRef = React.createRef<Text>();

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

The methods [of current] are available on most of the default components provided by React Native. Note, however, that they are not available on composite components that aren't directly backed by a native view. This will generally include most components that you define in your own app. - Direct Manipulation - React Native documentation

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

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