首页 > 解决方案 > 如何修复损坏的 TextInput 值更新程序

问题描述

我试图让文本输入从右到左打印数量,这样......

... 等等。我的问题是,当我每按 3 次按键执行此操作时,输入会添加之前的 3 次按键,并且时不时地会按随机键。我究竟做错了什么?

我试图收集按键并将击键组合添加到状态对象中,然后通过格式化助手方法运行它,最后将该值设置为 textinput 的 value 属性,但它不起作用。我已经断断续续地这样做了好几个星期了,如果有任何帮助,我将不胜感激!

class EnterAmount extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            num: "",
            concatNum:""
        };
        this.handleKeyPress = this.handleKeyPress.bind(this);
    }

    printNum = (num) => {
        if(num.length === 0) {
            return '$0.00'
        } else if (num.length === 1) {
            return '$0.0' + num;
        } else if (num.length === 2) {
            return '$0.' + num
        } else {
            return '$' + num.slice(0, num.length - 2) + '.' + num.slice(num.length - 2, num.length)
        }
    }

    handleKeyPress(key) {
        console.log(key);
        if(key !== '.') { 
            this.setState(prevState=>({concatNum: prevState.concatNum + key}))
            this.setState(prevState => ({ num:  this.printNum(prevState.concatNum)}))
        }
    }

    render() {
        return (
            <TouchableWithoutFeedback>
                <View>
                    <View>
                        <Text>Custom Amount</Text>
                        <View>
                            <TextInput 
                                style={styles.input}
                                keyboardType={'numeric'}
                                returnKeyType={'done'}
                                onKeyPress={(e) => {this.handleKeyPress(e.nativeEvent.key)}}
                                value={this.state.num}
                            />
                        </View>
                    </View>
                </View>
            </TouchableWithoutFeedback>
        );
    }
}

标签: react-native

解决方案


推荐阅读