繁体   English   中英

React onChange 事件返回 TypeError: props.handleChange is not a function

[英]React onChange event returns a TypeError: props.handleChange is not a function

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

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

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

props.handleChange 不是函数

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

App class 组件:

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;

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

捆绑;

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

箭头 function;

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

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

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

在您的构造函数中,您没有正确绑定 function

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM