类型错误:无法读取未定义的属性“handleChange”

我正在尝试使用 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;


繁星淼淼
浏览 161回答 1
1回答

收到一只叮咚

因为this是函数范围的,箭头函数除外。const todoComponents = this.state.todos.map(task => (&nbsp; &nbsp; <List key={task.id}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; task={task}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handleChange={this.handleChange} />))或者,如果您必须使用function.const that = this;const todoComponents = this.state.todos.map(function (task) (&nbsp; &nbsp; <List key={task.id}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; task={task}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handleChange={that.handleChange} />));另见How to access the correct `this` inside a callback?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript