【问题标题】:ReactJS error when passing a function as a props将函数作为道具传递时出现 ReactJS 错误
【发布时间】:2021-01-20 21:21:52
【问题描述】:

最近我开始在教程的帮助下学习 ReactJS,但我遇到了一个我自己找不到解决方案的错误。我决定做的第一个项目是待办事项列表,当尝试将“handleChange”函数作为道具传递给我的组件时,我收到此错误TypeError: Cannot read property 'handleChange' of undefined

这是我的 App 类的完整代码,因此您可以看到我正在尝试做什么:

import React from 'react';
import './App.css';
import Content from "./Content"
import ToDoItems from "./ToDoItems"

class App extends React.Component {

  constructor() {
    super()
    this.state = {
      items: ToDoItems
    } 
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange() {
    console.log("Change!")
  }

  render() {
    const items = this.state.items.map(function(item){
      return (<Content key={item.id} todo={item.item} checked={item.completed} handleChange={this.handleChange}/>)
    })
    return (
      <div>
        {items}
      </div>
    )
  }
}

export default App;

我正在从名为 ToDoItems 的文件中获取我的数据,并尝试将它们作为道具传递给 Content 组件。在我尝试传递函数 handleChange() 之前,一切正常。

我一定是做错了什么。任何帮助将不胜感激。

【问题讨论】:

    标签: javascript html reactjs jsx


    【解决方案1】:

    问题来了,

    const items = this.state.items.map(function(item){
          return (<Content key={item.id} todo={item.item} checked={item.completed} handleChange={this.handleChange}/>)
        })
    

    当你使用非数组函数时,它会将this 和其他东西绑定到它自己的原型上。意思是你的this.handleChanges this实际上是指函数,而不是类

    试试这个,

    const items = this.state.items.map((item) => {
    //                                 ^^^^^^^^^^^
          return (<Content key={item.id} todo={item.item} checked={item.completed} handleChange={this.handleChange}/>)
        })
    

    因为箭头函数不绑定this 或任何其他东西。所以this 现在应该引用类

    【讨论】:

    • 哦,哇,这很快又很有帮助!谢谢,这解决了我的问题。关于为什么它实际上需要箭头函数的任何简短解释?
    • @simonugor 很高兴能提供帮助。不要忘记将其标记为答案和支持
    猜你喜欢
    • 2021-04-13
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-05
    • 2022-08-12
    • 2018-01-31
    相关资源
    最近更新 更多