[英]value is NaN after parseInt() in react-native TextInput
我正在尝试从<TextInput>
中的state
设置一个 Int 值,方法是首先将其转换为string
( <TextInput>
只能接收一个字符串),然后我希望能够更改该值并使用新的<TextInput/>
值。 当我尝试更改<TextInput/>
中的值时
我收到错误: undefined is not an object (evaluating 'this.state.keys.toString')
更新:
我从this.keyInt
中删除了this
,现在我在输入更新时收到NaN
,但错误消失了
React-Native代码:
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
keys: 0,
id: this.props.id
};
}
updateKeysWithInputHandler = (e) => {
keyInt = parseInt(e.target.value);
console.log(`keyInt is: ${keyInt}`);
this.setState({
keys: keyInt
})
}
render() {
return (
<View style={styles.container}>
<TextInput
id={this.props.id}
style={styles.title}
keyboardType='numeric'
maxLength={2}
value={this.state.keys.toString()}
onChange={this.updateKeysWithInputHandler}
/>
</View>
);
}
好了,感谢这篇文章以及Adam Azad的帮助,我解决了我的问题。
显然,react-native <TextInput/>
不使用target
,而是使用nativeEvent.text
所以我更改了代码,现在可以使用了。
工作代码:
updateKeysWithInputHandler = (val) => {
keyInt = parseInt(val);
console.log(val);
this.setState({
keys: keyInt
})
}
render() {
return (
<View style={styles.container}>
<TextInput
id={this.props.id}
style={styles.title}
keyboardType='numeric'
maxLength={2}
value={this.state.keys.toString()}
onChange={(event) => this.updateKeysWithInputHandler(event.nativeEvent.text)}
/>
</View>
);
}
}
this.setState({
keys: this.keyInt
// ___^^^^^
})
删除this
关键字,因为它将上下文从当前范围更改为Counter
范围,其中keyInt
变量。
为什么keys: this.keyInt
?
它不应该是keys: keyInt
吗?
updateKeysWithInputHandler = (e) => {
if (isNaN(event.target.value) || event.target.value.toString().length===
0) {
event.target.value = 0;
}
this.setState({
keys: parseInt(event.target.value)
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.