清除TextInput文本时清除状态

问题描述 投票:0回答:3

当我清除textInput时,我试图清除我之前设置的字符串。我试过下面的代码,但它没有清除状态中的字符串。我做错了什么,请求?

<TextInput
    ref={(el) => this.myInput = el}
    onChangeText={this.onChangeText}
    text={this.state.mytext}
    placeholder='Enter Text'
    placeholderTextColor='#999'
    keyboardType='numeric'
    returnKeyType='next'
/>

onChangeText = (t) => {
    this.props.setData('mytext', t)
    if(t == ''){
        this.setState({
            newText: ''
        })
    }
}
react-native textinput
3个回答
0
投票

您没有将value财产传递给TextInput。在您的情况下,TextInput不知道要查找哪个值。

 <TextInput
     value={this.state.yourValue}
     onChangeText={yourValue => this.setState({ yourValue }) }
 /> 

0
投票

嗯问题是我猜的是道具。不太确定在text是否有一个名为TextInput的道具。此外,如果可能想要在没有检查的情况下使用setState进行更改。

<TextInput
    ref={(el) => this.myInput = el}
    onChangeText={this.onChangeText}
    value={this.state.mytext}
    placeholder='Enter Text'
    placeholderTextColor='#999'
    keyboardType='numeric'
    returnKeyType='next'
/>

onChangeText = (t) => {
    this.props.setData('mytext', t);
    this.setState({
       newText: t
    });
}

0
投票

您的问题是您没有更新TextInput使用的值。您将状态值设置为newValue,但是您尝试在组件中将其用作this.state.myText

因此,基于下面的注释,当newText为空字符串时,您似乎希望将myText的值设置为空字符串。

首先,我们应该使用正确的prop value来显示字符串的正确值。

其次我们应该处理onChangeText函数中状态的变化。请注意,在重构的onChangeText中,我们检查以确保传递给它的文本的值等于空字符串。如果是,那么我们更新newTextmyText的值,否则如果它不是空字符串,那么我们只更新myText的值,以便TextInput中显示的值是正确的。

<TextInput
    ref={(el) => this.myInput = el}
    onChangeText={this.onChangeText}
    value={this.state.myText}
    placeholder='Enter Text'
    placeholderTextColor='#999'
    keyboardType='numeric'
    returnKeyType='next'
/>

onChangeText = (t) => {
    this.props.setData('mytext', t)
    if(t === ''){
        this.setState({ newText: '', myText: '' })
    } else {
      this.setState({ myText: t})
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.