繁体   English   中英

react-native TextInput 中的 parseInt() 之后的值为 NaN

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM