我正在向 TextInput 组件的输入文本添加一些验证。
TextInput 的值在状态中处理,并且仅在输入的值有效时更新。
我的代码看起来像这样:
class TextInputWithValidation extends Component {
constructor(props) {
super(props);
this.state = { text: ''}
this.handleChange = this.handleChange.bind(this);
}
handleChange(text) {
if(isValid) {
this.setState({text})
}
}
render() {
return (
<TextInput
value={this.state.text}
onChangeText={this.handleChange}
/>
)
}
}
问题是,当向 TextInput 输入无效字符时,无效文本会出现一秒钟然后消失 - 这会导致不必要的闪烁。
有什么想法如何解决这个问题吗?
根据您的评论,解决方法可能是使用您的handleChange方法来检测小数点,然后简单地设置某种inputLengthState
到小数点的当前位置
然后你可以使用 prop 进行文本输入maxLength = this.state.inputLengthState + this.state.precision
,精度为小数点后的位数。我在下面写了一些基本代码
class TextInputWithValidation extends Component {
constructor(props) {
super(props);
this.state = {
text: '',
precision: 2,
inputLength: 100,
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(text) {
if(isValid) {
this.setState({text})
}
//somewhere here you would check text for a decimal place
//and then set the inputLength the decimals' string index. If null,
//set it to some limit however you would like ( i used 100 ).
}
render() {
return (
<TextInput
value={this.state.text}
maxLength={this.state.inputLength + this.state.precision}
onChangeText={(text) => {this.handleChange(text)}}
/>
)
}
}
如果我的代码有点语法错误,我很抱歉,已经有一段时间了。对于检查小数位的算法,我确信这应该非常简单。如果没有,请说。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)