更改动态 TextInput 上的文本值
2020-10-01
147
我正在尝试使用 javscript 和 expo 添加简单的 textInput,一切都运行良好,除了尝试更改文本的值时出现错误
我尝试了很多方法但都不起作用
const AccountsAddScreen = props => {
const [inputList, setInputList] = useState([{accountName : ""}]);
const handleInputChange = (e, index) => {
const list = [...inputList]
const {accountName, value } = e.target
list[index][accountName] = value;
setInputList(list);
};
const handleRemoveClick = index => {
const list = [...inputList];
list.splice(index, 1);
setInputList(list);
}
const handleAddClick = () => {
setInputList([...inputList, {accountName : ''}]);
}
console.log(single)
return (
<View style = {styles.container}>
<Text>
We are Testing
</Text>
<View>
{
inputList.map((x, i) => {
return (
<View key = {i}>
<TextInput
placeholder = 'Add Account Name'
style = {styles.input}
value = {x.accountName}
onChangeText = {e => handleInputChange(e, i)}
/>
{
inputList.length !== 1 && <Button title = 'Remove' onPress = {()=> { handleRemoveClick(i)}}/>
}
{
inputList.length - 1 === i && <Button title = 'Add' onPress = {handleAddClick} />
}
</View>
);
})
}
</View>
</View>
);
}
const styles = StyleSheet.create({
input : {
borderColor : 'black',
borderWidth : 1
}
});
export default AccountsAddScreen;
我收到的错误是
TypeError: undefined is not an object (evaluating '_e$target.accountName')
2个回答
const {accountName, value } = e.target
list[index][accountName] = value;
应为
const { value } = e.target
list[index].accountName = value;
Syed Mishar Newaz
2020-10-01
您必须像下面这样操作。
const handleInputChange = (e, index) => {
const list = [...inputList];
list[index]['accountName'] = e;
setInputList(list);
};
'e' 保存更新文本的值,您可以简单地将其设置为您传入 i 的索引中的值。
Guruparan Giritharan
2020-10-01