当我清除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: ''
})
}
}
您没有将value
财产传递给TextInput
。在您的情况下,TextInput
不知道要查找哪个值。
<TextInput
value={this.state.yourValue}
onChangeText={yourValue => this.setState({ yourValue }) }
/>
嗯问题是我猜的是道具。不太确定在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
});
}
您的问题是您没有更新TextInput
使用的值。您将状态值设置为newValue
,但是您尝试在组件中将其用作this.state.myText
。
因此,基于下面的注释,当newText
为空字符串时,您似乎希望将myText
的值设置为空字符串。
首先,我们应该使用正确的prop value
来显示字符串的正确值。
其次我们应该处理onChangeText
函数中状态的变化。请注意,在重构的onChangeText
中,我们检查以确保传递给它的文本的值等于空字符串。如果是,那么我们更新newText
和myText
的值,否则如果它不是空字符串,那么我们只更新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})
}
}