React onChange事件返回TypeError:props.handleChange不是函数

问题描述 投票:0回答:3

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

我试图从名为handleChange的子功能组件中调用此TodoItem方法。

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

props.handleChange 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
3个回答
1
投票

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

绑定;

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

箭头功能;

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

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

P.S.2:您实际上调用了handleChange而不是将其绑定到构造函数中。


0
投票

您只需要远程this.handleChange = this.handleChange(this);绑定。


0
投票

在构造函数中,您未正确绑定您的函数

© www.soinside.com 2019 - 2024. All rights reserved.