react-native - 如何修复损坏的 TextInput 值更新程序
问题描述
我试图让文本输入从右到左打印数量,这样......
- 默认值:“$0.00”,
- 用户输入 1: "$0.01",
- 用户输入 2:“$0.12”,
- 用户输入 3: "$1.23",
- 用户输入 4:“$12.34”
... 等等。我的问题是,当我每按 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>
);
}
}
解决方案
推荐阅读
- python - 如何为 python setter 提供有效的文档字符串或帮助?
- azure - 如何使用专用终结点通过 VPN 网关连接到 Azure SQL 数据库
- shell - 使用 Oozie 检查 HDFS 位置中是否存在大小大于零的文件
- python - 如何使用只有 3 行的 python tkinter 制作 Treeview。默认情况下会显示包含多行的树视图
- c - 链表函数在正常调用时有效,但在IF语句中调用时不起作用?
- python - 没有足够的背景过滤
- python - Django ModuleNotFoundError。一切都很好,但我无法运行服务器
- python - Paraview 中的摄像机轨迹记录
- json - 使用 mongofiles 检索文件会导致 JSON 错误
- laravel - 我想从 Laravel 关系中提取与 where 子句匹配的前五个数据