gpt4 book ai didi

javascript - 即使父状态更新,复选框也不会更新对子项的 react ?

转载 作者:行者123 更新时间:2023-12-01 03:34:05 24 4
gpt4 key购买 nike

这是来自父级的代码:

_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))}
/>
)}

这是我尝试过的,因为在复选框上分配 Prop 不会更新子待办事项代码,检查可以是 true 或 false,这取决于 props:

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>

如果你想将child的checked属性也保留为child的状态,那么Mayank所说的componentWillReceiveProps将是正确的方法。

关于javascript - 即使父状态更新,复选框也不会更新对子项的 react ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44376687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com