【发布时间】:2022-01-18 00:33:23
【问题描述】:
我有一个简单的表格。您单击“添加项目”按钮并出现一个文本框。模糊时,在文本框中输入的文本被添加到状态变量数组中。再次单击“添加项目”按钮,出现另一个文本框,依此类推。
对于每个文本框,还有一个“删除项目”按钮。单击此按钮时,当前项从数组中移除,当前文本框从页面中移除。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
items: []
}
}
addItem() {
this.setState({
items: [...this.state.items, []]
}
)
}
removeItem(index) {
//var items = this.state.items;
var items = [...this.state.items];
items.splice(index, 1);
this.setState({
items: items
})
}
changeItem(e, index) {
var items = this.state.items;
items[index] = e.target.value;
this.setState({
items: items
})
}
render() {
return (
<div>
{
this.state.items.map((item, index) => {
return (
<React.Fragment key={index}>
<hr />
<Row>
<Col column sm="8">
<Form.Control
type="text"
name="item"
onBlur={(e) => this.changeItem(e, index)}
/>
</Col>
</Row>
<Row>
<Col column sm="8">
<Button
onClick={() => this.removeItem(index)}
variant="link"
size="sm">
Remove Item
</Button>
</Col>
</Row>
</React.Fragment>
)
})
}
<br />
<Button
onClick={(e) => this.addItem(e)}
variant="outline-info">Add item
</Button>
</div>
)
}
}
我遇到的问题是,虽然数组在removeItem(index) 中修改成功,但从页面中删除的文本框始终是最后添加的,而不是应该删除的。例如:
- 点击“添加项目”,输入:aaa
items: ['aaa'] - 点击“添加项目”,输入:bbb
items: ['aaa', 'bbb'] - 点击“添加项目”,输入:ccc
items: ['aaa', 'bbb', 'ccc'] - 点击aaa下的“删除项目”。项目成功更新:
items: ['bbb', 'ccc']
页面应该显示一个带有 bbb 的文本框和一个带有 ccc 的文本框。但它显示:
如何从页面中删除正确的文本框?
【问题讨论】:
-
你不应该在
removeItem函数中使用splice,因为splice改变了它正在处理的数组,所以基本上你在不使用setState函数的情况下改变了状态,这是不正确的在反应。相反,您应该使用[...this.state.items]创建一个具有相同内容的新数组,然后在该新数组上使用splice,然后使用该新数组设置状态。 -
` items: [...this.state.items, []]` 添加的项目看起来不正确。 ` items: [...this.state.items, '']` .其他一切看起来都很好
-
尝试在文本框中添加一个键
-
@RishabhGupta - 我确实在 removeItem() 中创建了一个新数组。我没有直接修改状态。如果你打算在 addItem() 中这样做,我试过了,但我仍然遇到同样的问题。
-
@RishabhGupta - 我更新了代码,但我仍然遇到同样的问题。
标签: javascript reactjs react-native