如何在React Native中对动态添加的TextInput输入值求和
存在的问题
- 不应该将TextInput组件直接存储在state中,state应该只存储业务数据,UI组件应当在render方法中基于数据动态生成,原写法会导致组件状态无法正确关联更新。
- 输入框的onChangeText逻辑错误:当前每次输入都会将当前输入的字符追加到FinalVal数组末尾,无法对应到对应输入框的完整值,比如在同一个输入框输入
12,会给FinalVal新增两个元素'1'、'2',而不是将第一个位置的值更新为'12',多输入框场景下完全无法区分值对应的输入框。 - 求和的for循环边界错误:循环条件写为
i <= this.state.FinalVal.length,会多遍历一次下标等于数组长度的位置,该位置的值为undefined,转Number后得到NaN,最终总和会变成NaN。
修正方案
调整state结构,仅存储所有输入框的值,添加输入框时给值数组新增空元素,渲染时遍历值数组生成对应的TextInput,修改值时直接更新对应下标位置的内容,求和时正确遍历数组即可。
修正后的完整代码如下:
import React, { Component } from 'react'; import { Text, View, StyleSheet, TouchableOpacity, TextInput, } from 'react-native'; class App extends Component { constructor(props) { super(props); this.state = { inputValues: [], sum: 0, }; } addNewInput = () => { this.setState({ inputValues: [...this.state.inputValues, ''] }); }; handleInputChange = (index, value) => { const newInputValues = [...this.state.inputValues]; newInputValues[index] = value; this.setState({ inputValues: newInputValues }); }; calculateSum = () => { const total = this.state.inputValues.reduce((sum, curr) => { return sum + (Number(curr) || 0); }, 0); this.setState({ sum: total }); }; render() { return ( <View style={styles.container}> <TouchableOpacity style={styles.AddBtn} onPress={this.addNewInput}> <Text>Click to add new Field</Text> </TouchableOpacity> <TouchableOpacity style={styles.AddBtn} onPress={this.calculateSum}> <Text>Calculate</Text> </TouchableOpacity> <View> {this.state.inputValues.map((val, index) => ( <TextInput key={index} style={styles.FieldNew} keyboardType="numeric" value={val} onChangeText={(text) => this.handleInputChange(index, text)} /> ))} </View> <Text>Sum is : {this.state.sum}</Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#ecf0f1', padding: 8, }, AddBtn: { marginTop: 30, fontSize: 18, fontWeight: 'bold', textAlign: 'center', }, FieldNew: { borderColor: 'red', borderWidth: 1, marginBottom: 5, }, }); export default App;
内容的提问来源于stack exchange,提问作者user17473297
相关产品推荐
相关产品推荐

