这是父母的代码:
_handleSelectedTodo(e) {
e.preventDefault();
this.setState({checkedIds: [...this.state.checkedIds, e.target.value]});
}
// render () { ...
<ul>
{todos.map((todo,todoIndex) => // The map method has default argument on second index, the index of the current todo in map execution. We use it so we do not have to use findIndex when we need to dispatch action that needs index of a specific todo
<Todo
key={todo.id}
{...todo} // pass all the todo property
onClick={() => onTodoClick(todo.id)}
onTrashClick={() => onDeleteClick(todoIndex)}
handleSelectedTodo = {this._handleSelectedTodo}
checked={Boolean(this.state.checkedIds.includes(todo.id))}
/>
)}
这是我尝试过的,因为在复选框上分配道具未更新子托多代码上,检查的是true或false,它取决于道具:
componentWillMount() {
this.setState({ checked: this.props.checked })
}
// render() { ...
<input
checked={this.state.checked}
onChange={handleSelectedTodo}
type="checkbox"
value={id}
></input>
检查复选框更新父零件状态,但未检查儿童的复选框。帮助?
也可以以这种方式编写此代码: -
_handleSelectedTodo(e) {
e.preventDefault();
this.setState({checkedIds: [...this.state.checkedIds, e.target.value]});
}
render () { ...
<ul>
{todos.map((todo,todoIndex) => {
let isChecked = (this.state.checkedIds.indexOf(todo.id) >= 0);
return (
<Todo
key={todo.id}
{...todo} // pass all the todo property
onClick={(id) => onTodoClick(todo.id)} //This event should be binded to 'this' inside the constructor
onTrashClick={(todoIndex) => onDeleteClick(todoIndex)}
handleSelectedTodo = {this._handleSelectedTodo}
checked={isChecked}
/>
)
});
}
该子组件应取决于其父状态的检查属性
<input
checked={this.props.checked}
onChange={handleSelectedTodo}
type="checkbox"
value={id}
></input>
如果您也想将儿童的签到财产保留为儿童状态,那么Mayank对ComponentWillReceiveProps的评价将是正确的方法。
原因是, componentWillMount
仅在不在此之后的初始渲染之前才会被调用,当您更新父级组件的 state
时,儿童组件的 state
不会更新。
使用 componentWillReceiveProps
方法更新儿童组件的state
:
componentWillReceiveProps(nextProps){
if(nextProps.checked != this.state.checked)
this.setState({checked: nextProps.checked})
}
或最简单的解决方案将不会保存在儿童组件的state
中,直接使用props
值,例如:
<input
checked={this.props.checked} //here use this.props.checked directly
onChange={handleSelectedTodo}
type="checkbox"
value={id}
>
</input>
componentWillReceiveProps:
componentWillReceiveProps((是在安装的组件之前调用的 收到新的道具。如果您需要更新状态 道具更改(例如,要重置它(,您可以比较此。 和NextProps并使用this.setState((在 此方法。
componentWillmount:
componentwillmount((在安装之前立即调用。它 在渲染((。
之前称为