如何在React Native中使用ref清除Text组件

时间:2019-04-04 10:31:11

标签: javascript reactjs react-native

我想在超时时使用ref清除文本组件,但找不到。

<Text style={{ color: "#fff" }} ref={text => this._text = text}>
              {isKeyValid === undefined
                ? null
                : isKeyValid
                ? "Key is been verified."
                : "Your key is invalid or expired."}
</Text>

clearErrorMessages = () => {
   setTimeout(() => {
   //something like that here which i have no idea  
   this._text.clear() 
   }, 2000);
}

关于这个家伙的任何想法,谢谢...

2 个答案:

答案 0 :(得分:2)

没有方法清除<Text>组件中的文本。 您可以执行以下操作:取想要在状态变量中显示的任何值,并在需要时将其设置为空字符串。

在构造函数中:

this.state={
  value:"myvalue",
}

在渲染中

<Text>{this.state.value}</Text>

然后在要清除文本的任何操作/功能上执行以下操作:

this.setState({value:""});

答案 1 :(得分:1)

您可以采用与引用不同的方法,

采用一种状态,默认情况下在构造函数中将其设置为false, 并在超时后将其设置为true。另外,根据情况使用 看到这个

<Text style={{ color: "#fff" }} ref={text => this._text = text}>
              {isKeyValid === undefined && this.state.isCleared
                ? null
                : isKeyValid
                ? "Key is been verified."
                : "Your key is invalid or expired."}
</Text>

clearErrorMessages = () => {
   setTimeout(() => {
   //something like that here which i have no idea  
   this.setState({isCleared:true});
   }, 2000);
}

不要忘记在构造函数中对其进行初始化。