React Native - 使用状态时文本输入闪烁 [英] React Native - text input blinking when using state
问题描述
我正在向 TextInput 组件的输入文本添加一些验证.TextInput 的值在状态中处理,并且仅在输入的值有效时更新.
I'm adding some validation to the input text of a TextInput component. The TextInput's value is handled in the state and is only updated when the value entered is valid.
我的代码如下:
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 输入无效字符时,无效文本会出现一秒钟然后消失 - 导致不必要的眨眼.
The problem is that when entering a non valid character to the TextInput the non valid text appears for a second and the disappears - what causes an unwanted blink.
任何想法如何解决这个问题?
Any ideas how to solve this?
推荐答案
根据您的评论,解决方法可能是使用您的 handleChange 方法来检测小数点,然后简单地设置某种 inputLengthState
到小数点的当前位置
Based on your comment, a work around could be to use your handleChange method to detect for a decimal point, and then simply set some sort of inputLengthState
to the current location of the decimal
然后你可以使用文本输入的 prop maxLength = this.state.inputLengthState + this.state.precision
,精度是你的小数位.我在下面写了一些基本代码
Then you can use the prop for text input maxLength = this.state.inputLengthState + this.state.precision
, with precision being your decimal places. Ive written some basic code below
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)}}
/>
)
}
}
抱歉,如果我的代码在语法上有点偏离,已经有一段时间了.对于检查小数位的算法,我相信这应该非常简单.如果没有,请说.
Apologies if my code is a bit off syntax wise, it has been a little while. For the algorithm to check for the decimal place, I'm sure this should be pretty straight forward. If not, say.
这篇关于React Native - 使用状态时文本输入闪烁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!