我正在尝试使用 React 构建一个待办事项列表应用程序。收到错误“无法读取未定义的 handleChange 属性”。下面是我正在处理的代码。此外,todosData 是一个对象数组,具有 id、text 和 completed(boolean - true/false) 作为属性。 import React from "react"; import './App.css'; import List from './Components/Todo-Startup/content'; import todosData from './Components/Todo-Startup/todosData'; class App extends React.Component { constructor(){ super() this.state = { todos: todosData } this.handleChange = this.handleChange.bind(this) } handleChange(id){ console.log("Changed", id) } render() { const todoComponents = this.state.todos.map(function(task){ return ( <List key={task.id} task={task} handleChange={this.handleChange} /> ) }) return ( <div className = "App"> {todoComponents} </div> ) } } export default App;content.js 如下,import React from 'react';const List = function (props){ return ( <div className="todo-list"> <input onChange={function(){props.handleChange(props.task.id) }} type="checkbox" checked={props.task.completed}/> <p>{props.task.text}</p> </div> );}export default List;最后是数组 todosData, const todosData = [ { id: 1, text: "Take out the trash", completed: true }, { id: 2, text: "Grocery Shopping", completed: false }, { id: 3, text: "Get a hair cut", completed: true }, { id: 4, text: "Study & Practice JavaScript", completed: true } ]export default todosData;
1 回答
收到一只叮咚
TA贡献1821条经验 获得超4个赞
因为this是函数范围的,箭头函数除外。
const todoComponents = this.state.todos.map(task => (
<List key={task.id}
task={task}
handleChange={this.handleChange} />
))
或者,如果您必须使用function.
const that = this;
const todoComponents = this.state.todos.map(function (task) (
<List key={task.id}
task={task}
handleChange={that.handleChange} />
));
另见How to access the correct `this` inside a callback?
添加回答
举报
0/150
提交
取消