[英]React onChange event returns a TypeError: props.handleChange is not a function
I created a simple class method called handleChange
with a parameter of id
under the class App
.我在 class
App
下创建了一个名为handleChange
的简单 class 方法,其参数为id
。
I tried to call this handleChange
method from a child function component called TodoItem
.我尝试从名为
TodoItem
的子 function 组件调用此handleChange
方法。
When I clicked on the checkbox, the browser returned a TypeError
saying that props.handleChange(props.item.id) is not a function
, as shown in the pictures:当我点击复选框时,浏览器返回一个
TypeError
说props.handleChange(props.item.id) is not a function
,如图所示:
Can someone explain what is wrong on my codes in TodoItem
?有人可以解释我在
TodoItem
中的代码有什么问题吗?
App
class component: 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
functional component: 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;
You either need to bind handleChange
on using or convert it into arrow functions.您需要在使用时绑定
handleChange
或将其转换为箭头函数。 I prefer arrow functions.我更喜欢箭头功能。
binding;捆绑;
this.handleChange = this.handleChange.bind(this);
arrow function;箭头 function;
handleChange = (id) => {
console.log("changed", id);
}
PS: if you don't change the item in the child component there is no point to pass item into child and pass item.id to props.handleChange since it is accessible in the parent component in the first place. PS:如果您不更改子组件中的项目,则将 item 传递给 child 并将 item.id 传递给 props.handleChange 是没有意义的,因为它首先可以在父组件中访问。
PS2: you actually invoke handleChange
instead of binding it in your constructor. PS2:您实际上是调用
handleChange
而不是在构造函数中绑定它。
In your constructor you're not properly binding your function在您的构造函数中,您没有正确绑定 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.