我有一个呈现TextInput
的组件,并且已经为该子组件分配了ref
:
return (
<View>
<TextInput
ref={ref => (this.textInput = ref)}
// ...props
}}
/>
// ...other stuff
)}
</View>
);
按照Flow website的说明,我将实例属性设置为类型?TextInput
:
export class AutoFillMapSearch extends React.Component<Props, State> {
textInput: ?TextInput;
// ...
Flow将此作为ref
的类型。但是,当我写this.textInput.blur();
时,Flow抱怨道:
Cannot call this.textInput.blur because property 'blur' is missing in null or undefined.
我了解到ref
是一种可能的类型,因此我有点理解为什么会出现此错误,但是我不知道该如何解决。
(该应用程序很好用,只是Flow在这里抱怨。)
答案 0 :(得分:1)
ref
在组件生命周期的某些时间可以为空:https://reactjs.org/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element
为了防止这种情况,您需要在使用ref之前检查其是否为null。为此,您可以使用if
语句,也可以按照评论中的@Marko Savic的建议使用this.textInput && this.textInput.blur()
。