这是我的代码的简化示例
constructor(props) {
super(props);
this.state = {
components:[ComponentA, ComponentA, ComponentA, ComponentA, ComponentA ]
}
}
hide(i){
let components= this.state.components.filter((item,k)=>k!=i);
this.setState({components});
}
render() {
return (<div>
{this.state.components.map((item,i) => {
let ChildComponent = item;
return <div key={i} onClick={()=>this.hide(i)}>
<ChildComponent />
</div>
})
}
在这里,我有相同组件的实例。当我单击一个时 - 我希望删除具有此特定实例的 div。要检查 - 这是我的 ComponentA 代码:
constructor(props) {
super(props);
this.state = {
uid: Math.random()
}
}
render() {
return (
<div>
ComponentA - {this.state.uid}
</div>
);
}
因此,每个实例都有其唯一的 uid 状态。当我单击其中一个组件时 - 总是最后一个被删除。
更新
那是简化版,现在可以使用了。我真正的问题是 react-grid-layout:
this.state = {
testlayout: [
{"w": 10,"h": 100,"i": 0,"x": 0, "y": 0,"widget": Component4},
{"w": 10,"h": 100,"i":1,"x": 10, "y": 0,"widget": Component4},
{"w": 10,"h": 100,"i": 2,"x": 20, "y": 0,"widget": Component4},
]
}
onClose(i){
let testlayout = this.state.testlayout.filter((item,k)=>item.i!=i);
this.setState({testlayout});
}
render() {
return (<div>
<ReactGridLayout>
{this.state.testlayout.map((item, i) => {
let ChildComponent = item.widget;
return
<div onClick={() => this.onClose(item.i)} data-grid={this.state.testlayout[i]} key={item.i}>
<ChildComponent/>
</div>
}
)}
</ReactGridLayout>
</div>
);
}