在响应本机TextInput创建引用时出现打字稿问题

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

我在定义引用时遇到了一个问题,即

inputRef = React.createRef(null)

//...

const someFunction () => {
 if (this.inputRef && this.inputRef.current) {
   this.inputRef.current.focus()
 }
}

//...

<TextInput ref={inputRef} />
Run Code Online (Sandbox Code Playgroud)

在我访问的地方出现.focus()以下错误

[ts]属性“焦点”在类型“从不”上不存在。[2339]

我能以某种方式告诉我createRef这个ref可以为null或TextInput,以便它知道.focus()可以存在吗?

Pet*_*uzs 17

您可以尝试以下操作:

inputRef = React.createRef<TextInput>();
Run Code Online (Sandbox Code Playgroud)