假设您将子组件保存在一个列表中。您可以在州内拥有它。
inputList: []
假设父组件上有一个添加子组件的按钮。它的代码看起来与此类似。
<div>
<Button variant= "light" className="button" onClick={this.onAddAnotherBtnClick}>
Add Another
</Button>
{this.state.inputList.map(function(input, index) {
return input;
})}
</div>
(您可能必须像这样绑定 onAddAnotherBtnClick)。在该州,
this.onAddAnotherBtnClick = this.onAddAnotherBtnClick.bind(this);
onAddAnotherBtnClick 看起来像这样。
onAddAnotherBtnClick = (event) =>{
const inputList = this.state.inputList;
this.setState({
inputList: inputList.concat(<ChildComponent Id={inputList.length}
callbackDeleteButton={this.delete}/>)
});
}
这是删除方法。
delete = (Id) => {
delete this.state.inputList[Id];
this.setState({ inputList : this.state.inputList });
}
这是子组件上的删除按钮。
<Button variant= "light" className="button" onClick={this.onDeleteButtonClick}>
Delete
</Button>
这是 onDeleteButtonClick 方法。
onDeleteButtonClick = () => {
this.props.callbackDeleteButton(this.state.Id);
}
(您必须像这样在 State 中绑定方法)。
this.onDeleteButtonClick = this.onDeleteButtonClick.bind(this);
这里发生的情况是,当每个子组件在道具上创建时,我将 ID 发送给它。当子组件的删除按钮被点击时,它会通过父组件提供的回调方法将其 ID 发送给父组件。