gpt4 book ai didi

react-native - 使用 textInput React Native 更新处于 state 的数组对象中的元素

转载 作者:行者123 更新时间:2023-12-04 23:38:51 24 4
gpt4 key购买 nike

我在这里尝试做的是使用 textInput 更新数组对象“可用”,下面是我的代码。我不知道为什么它一直在 _update 函数行给我 token 错误。请帮忙。谢谢!

export class Inventory extends Component {
state = {
available: [
{id: 0, name: 'Xb', value:5},
{id: 1, name: 'Ad', value:19},
{id: 2, name: 'Sc', value:1},
{id: 3, name: 'AV', value:3},
{id: 4, name: 'Ba', value:8},
{id: 5, name: 'Ch', value:2},
{id: 6, name: 'Pr', value:9},
{id: 7, name: 'Mi', value:10},
{id: 8, name: 'Se', value:1},
],
}

_update = (text,index) => this.setState({available[index].value: text});

render(){
index = 0;
return(
<View style={styles.container}>
<TextInput style={styles.input}
keyboardType = 'number-pad'
returnKeyType = 'go'
autoCapitalize = 'none'
maxLength = {3}
value = {this.state.available[index].value}
onChange = {(text) => _update(text,index)} />
</View>
);
}

最佳答案

_update = (text,index) => this.setState({available[index].value: text}); 在某些方面无效。首先, setState 接受一个对象,如果您要更新值,该对象应该与您现在的状态相同的键和值。其次,available[index].value 不计算任何值,因为 available 未定义。您只能通过 available 访问 this.state.available 。第三,available[index].value 将成为新组件状态的关键,我认为这不是您想要的。

将您的更新更改为这样的

_update = (text, index) => {
const newArray = [...this.state.available];
newArray[index].value = text;
this.setState({ available: newArray });
}

关于react-native - 使用 textInput React Native 更新处于 state 的数组对象中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45262086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com