【问题标题】:React onChange event returns a TypeError: props.handleChange is not a functionReact onChange 事件返回 TypeError: props.handleChange is not a function
【发布时间】:2020-04-08 00:03:17
【问题描述】:

我在App 类下创建了一个名为handleChange 的简单类方法,其参数为id

我尝试从名为TodoItem 的子函数组件调用此handleChange 方法。

当我点击复选框时,浏览器返回一个TypeError,表示props.handleChange(props.item.id) is not a function,如图:

有人可以解释我在TodoItem 中的代码有什么问题吗?

App类组件:

import React, { Component } from "react";
import TodoItem from "./TodoItem";
import todosData from "./todosData";

class App extends Component {
  constructor() {
    super();
    this.state = {
      todos: todosData,
    };
    this.handleChange = this.handleChange(this);
  }

  handleChange(id) {
    console.log("changed", id);
  }

  render() {
    const todoItems = this.state.todos.map((item) => (
      <TodoItem key={item.id} item={item} handleChange={this.handleChange} />
    ));

    return <div className="todo-list">{todoItems}</div>;
  }
}

export default App;

TodoItem功能组件:

import React from "react";

function TodoItem(props) {
  return (
    <div className="todo-item">
      <input
        type="checkbox"
        checked={props.item.completed}
        onChange={(e) => props.handleChange(props.item.id)}
      />
      <p>{props.item.text}</p>
    </div>
  );
}

export default TodoItem;

【问题讨论】:

    标签: javascript reactjs onchange eventhandler


    【解决方案1】:

    您需要在使用时绑定handleChange 或将其转换为箭头函数。我更喜欢箭头功能。

    绑定;

    this.handleChange = this.handleChange.bind(this);
    

    箭头函数;

    handleChange = (id) => {
        console.log("changed", id);
    }
    

    P.S:如果您不更改子组件中的项目,则将 item 传递给子组件并将 item.id 传递给 props.handleChange 是没有意义的,因为它首先可以在父组件中访问。

    P.S.2:您实际上是调用 handleChange 而不是在构造函数中绑定它。

    【讨论】:

    • 谢谢你,ilkerkaran,正如你在代码中看到的那样,我确实在 App.js 下的 constructor() 中绑定了 handleChange。
    • @user13145130 我想你忘了绑定this.handleChange = this.handleChange.bind(this);
    【解决方案2】:

    在你的构造函数中你没有正确绑定你的函数

    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          todos: todosData,
        };
        this.handleChange = this.handleChange.bind(this)//<-- This is right
        //this.handleChange = this.handleChange(this);//<-- This is wrong
    }
    

    【讨论】:

    • 非常感谢您指出这个简单的错误。我正在排除故障,但无法发现这一点。我必须彻底检查我的眼睛。
    猜你喜欢
    • 1970-01-01
    • 2019-04-05
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2020-03-01
    • 2018-05-02
    • 1970-01-01
    相关资源
    最近更新 更多