Html 单击复选框不会';我不能改变它
我尝试使用handleChange方法更改负责复选框的已完成的布尔值,但它没有更改。。我找不到错过的地方Html 单击复选框不会';我不能改变它,html,reactjs,Html,Reactjs,我尝试使用handleChange方法更改负责复选框的已完成的布尔值,但它没有更改。。我找不到错过的地方 class App extends React.Component { constructor() { super() this.state = { todos: todosData } this.handleChange = this.handleChange.bind(this) }
class App extends React.Component {
constructor() {
super()
this.state = {
todos: todosData
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(id) {
this.setState((prevState) => {
const updatedTodos = prevState.todos.map(todo => {
if (todo.id === id) {
todo.completed = !todo.completed
}
return todo
})
return {
todos: updatedTodos
}
})
}
render() {
const todoItems = this.state.todos.map(item => <TodoItem key={item.id} item={item} handleChange={this.handleChange}/>)
return (
<div className="todo-list">
{todoItems}
</div>
)
}
}
export default App
类应用程序扩展了React.Component{
构造函数(){
超级()
此.state={
todos:todosData
}
this.handleChange=this.handleChange.bind(this)
}
手柄更换(id){
this.setState((prevState)=>{
const updatedTodos=prevState.todos.map(todo=>{
if(todo.id==id){
todo.completed=!todo.completed
}
返回待办事项
})
返回{
待办事项:更新的待办事项
}
})
}
render(){
const todoItems=this.state.todos.map(item=>)
返回(
{todoItems}
)
}
}
导出默认应用程序
这是我的ToDoItem组件
function TodoItem(props) {
return (
<div className="todo-item">
<input
type="checkbox"
checked={props.item.completed}
onChange={() => props.handleChange(props.item.id)}
/>
<p>{props.item.text}</p>
</div>
)
}
export default TodoItem
功能待办事项(道具){
返回(
props.handleChange(props.item.id)}
/>
{props.item.text}
)
}
将默认值导出到doItem
问题
您正在改变您的状态对象。当你不返回新的对象引用时,反应不考虑值不同,并用更新的值进行重命名。
if (todo.id === id) {
todo.completed = !todo.completed // <-- state mutation!
}
return todo // <-- same todo object reference
if(todo.id==id){
todo.completed=!todo.completed//todo.id==id{
……待办事项//
handleChange(id) {
this.setState((prevState) => ({
todos: prevState.todos.map(todo => todo.id === id ? {
...todo, // <-- shallow copy todo
completed: !todo.completed, // <-- update completed property
} : todo)
});
}