完成此操作的React方式是什么?按下按钮时删除选中的项目
我应该将复选框设置为子组件吗? - >如何将删除事件传递给子组件?
如果我不设置复选框为子组件将我的每个项目需要一个for循环中循环,并检查它是否是检查,如果为true,则删除
我敢肯定有一个优雅的解决方案但我对React很陌生,我还没有理解这些概念 - 所以如果有任何额外的阅读可以帮助提高我的理解,那么请让我知道!
完成此操作的React方式是什么?按下按钮时删除选中的项目
我应该将复选框设置为子组件吗? - >如何将删除事件传递给子组件?
如果我不设置复选框为子组件将我的每个项目需要一个for循环中循环,并检查它是否是检查,如果为true,则删除
我敢肯定有一个优雅的解决方案但我对React很陌生,我还没有理解这些概念 - 所以如果有任何额外的阅读可以帮助提高我的理解,那么请让我知道!
我现在可以想到的最简单的方法是拥有一个包含复选框(或至少复选框状态)数组的组件。该组件将显示复选框以及一个按钮,点击该按钮将迭代该数组并删除所有选中的框。
如果您不想将所有内容都保存在一个组件中,有多种方法可以实现此目的。例如,您可以轻松地将按钮和复选框数组保留在父组件中,并将数组作为通道传递给子组件。
您可能想看看flux,这是一种处理您的应用程序状态(复选框数组)的方法。流量的流行实现是redux。
您也可以使用React without flux(如上所示),这里有一篇关于8 no-flux stragergies for react component communication的文章。
基本上,父组件会跟踪子列表以及要删除的子列表。每选中一个复选框,它都被添加到删除列表中,并且如果未选中,则从删除列表中删除。当点击删除按钮时,删除列表中的每个项目都将从子列表中删除,删除列表将被清除,并调用setState来重新呈现组件。
import React from 'react';
import ReactDOM from 'react-dom';
class Form extends React.Component {
constructor(props) {
super(props)
}
// A delete-list and a list of children.
state = {
toDel: [],
checks: []
}
// Method called when checkbox is clicked.
recId = (idToDel) => {
// Grab the checkbox that was clicked.
let checker = document.getElementById(idToDel);
if (checker.checked) {
// Add the id to delete-list.
this.state.toDel.push(idToDel);
}
else {
// Remove the id from delete-list.
let index = this.state.toDel.indexOf(idToDel);
this.state.toDel.splice(index, 1);
}
}
// Method called when delete button is clicked.
del =() => {
// Loop through items to delete.
for (var i = 0; i < this.state.toDel.length; i++) {
// Convert id from string back to integer.
let index = parseInt(this.state.toDel[i])
// Replace the item to delete with empty string, so that every
// other element remains in place.
this.state.checks[index] = '';
}
// Re-render the component by calling setState.
this.setState({
toDel: [],
checks: this.state.checks
});
}
// Loading the component with child checkboxes. Children are handed
// parent methods as event handlers.
componentWillMount =() => {
for (var i = 0; i < 5; i++) {
this.state.checks.push(
<p key={i}>
<Check id={i.toString()} record={this.recId} />{i.toString()}
</p>
)
}
}
render() {
return (
<div>
{this.state.checks}
<button onClick={this.del}>Delete</button>
</div>
);
}
}
class Check extends React.Component {
constructor(props) {
super(props)
}
state = {}
render =() => {
// Call the parent method on click with proper context and pass
// id of this specific child back up to parent.
return (
<input type='checkbox' onClick={this.props.record.bind(null, this.props.id)} id={this.props.id} />
);
}
}
// Render component.
ReactDOM.render(
<Form />,
document.getElementById('test-container')
);