以下是我的代码的简化示例
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>
);
}
答案 0 :(得分:2)