我是 React 的新手,我似乎无法弄清楚这一点。我正在尝试在线练习,当我尝试在我的子组件上传递事件时,我收到错误“无法读取未定义的属性'handleClick'”错误。这是我的代码。import React from "react";import TodoItems from "./TodoItems";import TodoComponent from "./TodoComponent";class App extends React.Component { constructor() { super(); this.state = { todoanItem: TodoItems }; this.handleClick = this.handleClick.bind(this); } handleClick(id) { this.setState(function(state) { const newstate = state.todoanItem.map(function(todo) { if (todo.id === id) { todo.complete = !todo.complete; } return todo; }); return { todoanItem: newstate }; }); } render() { const theItems = this.state.todoanItem.map(function(item) { return ( <TodoComponent key={item.id} item={item} handleClick={this.handleClick} /> ); }); return <div>{theItems}</div>; }}export default App;import React from "react";class TodoComponent extends React.Component { render() { return ( <div className="todo-items"> <input type="checkbox" checked={this.props.item.completed} onChange={event => this.props.handleClick(this.props.item.id)} /> <p>{this.props.item.todo}</p> </div> ); }}export default TodoComponent;
1 回答
明月笑刀无情
TA贡献1828条经验 获得超4个赞
您需要在函数中使用箭头render函数App:
const theItems = this.state.todoanItem.map((item) => { // Here
return (
<TodoComponent
key={item.id}
item={item}
handleClick={this.handleClick}
/>
);
});
此外,在以下位置添加一个构造函数TodoComponent:
constructor(props) {
super(props);
}
添加回答
举报
0/150
提交
取消