【发布时间】:2018-11-25 18:09:39
【问题描述】:
我有一个状态数组,其中包含各种组件。当我单击其中一个组件上的删除按钮时,它会从数组中删除第一项。我似乎只有在使用数组中的组件时才会遇到这个问题,它适用于字符串数组。
父组件:
addItem = (block) => {
const add = [...this.state.items, block];
this.setState({items: add})
}
removeItem = (index) => {
const remove = [...this.state.items];
remove.splice(index, 1);
this.setState({items: remove})
}
render(){
return(
<div className="Board">
<div className="BoardContainer">
{this.state.items.map((item, index) => { return <Item remove= {this.removeItem} key={index} >{item}</Item>})}
</div>
<button onClick={() => this.addItem(<BannerImage />)}>Banner Image</button>
<button onClick={() => this.addItem(<ShortTextCentered />)}>Short Text Centered</button>
</div>
)
}
子组件:
export class Item extends React.Component {
handleRemove = () => {
this.props.remove(this.props.index)
}
render() {
return (
<div className="item">
{this.props.children}
<button onClick={this.handleRemove} >Remove</button>
</div>
)
}
}
【问题讨论】:
标签: javascript arrays reactjs