Html 复选框未选中单击(反应)
我使用react创建了一个待办事项列表。我有一些问题,我想创建复选框,但我的复选框不起作用,我无法解决:(我不知道这有什么问题 我为每个任务设置了数据,然后我需要更改某些任务的已完成数据,但它无法单击并更改已完成的任务 这是我的密码Html 复选框未选中单击(反应),html,reactjs,Html,Reactjs,我使用react创建了一个待办事项列表。我有一些问题,我想创建复选框,但我的复选框不起作用,我无法解决:(我不知道这有什么问题 我为每个任务设置了数据,然后我需要更改某些任务的已完成数据,但它无法单击并更改已完成的任务 这是我的密码 class App extends React.Component { constructor() { super() this.state = { todos: todoData, } this.handleChan
class App extends React.Component {
constructor() {
super()
this.state = {
todos: todoData,
}
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
// console.log(todo.completed)
}
return todo
})
return {
todos: updatedTodos
}
})
}
render() {
const todoItem = this.state.todos.map(item => <TodoItem key={item.id} item={item}
handleChange={this.handleChange}/>)
return (
<div>
<h1 className="header">My Todo Lists</h1>
{todoItem}
</div>
)
}
}
感谢您的帮助:)在您的
handleChange
上看起来,您正在对映射
转换上的现有状态进行变异。您必须返回一个新状态
用以下代码替换handleChange
:
handleChange(id){
this.setState((prevState)=>{
const updatedTodos=prevState.todos.map((todo)=>{
返回{
……待办事项,
完成:todo.id==id?!todo.completed:todo.completed
};
});
返回{
待办事项:更新的待办事项
};
});
}
在handleChange
上看起来,您正在对映射上的现有状态进行变异。您必须返回一个新状态
用以下代码替换handleChange
:
handleChange(id){
this.setState((prevState)=>{
const updatedTodos=prevState.todos.map((todo)=>{
返回{
……待办事项,
完成:todo.id==id?!todo.completed:todo.completed
};
});
返回{
待办事项:更新的待办事项
};
});
}
function TodoItem(props) {
let textItem = props.item.completed === true ?
<del>{props.item.text}</del> : props.item.text
return (
<div className="list">
<input
type="checkbox"
checked={props.item.completed}
onChange={() => props.handleChange(props.item.id)}
/>
<p className="item">{textItem}</p>
</div>
)
}
const todoData = [
{
id: 1,
text: "Practice coding",
completed: false
},
{
id: 2,
text: "Grocery shopping",
completed: true
},
{
id: 3,
text: "Wash the dishes",
completed: true
},
{
id: 4,
text: "Take out the trash",
completed: false
},
{
id: 5,
text: "Teach my brother homework",
completed: false
}
]