[我在类handleChange
下创建了一个简单的类方法id
,其参数为App
。
我试图从名为handleChange
的子功能组件中调用此TodoItem
方法。
当我单击复选框时,浏览器返回一个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;
您需要在使用时绑定handleChange
或将其转换为箭头功能。我更喜欢箭头功能。
绑定;
this.handleChange = this.handleChange.bind(this);
箭头功能;
handleChange = (id) => {
console.log("changed", id);
}
P.S:如果您不更改子组件中的项目,则没有意义将项目传递给子组件并将item.id传递给props.handleChange,因为它首先可以在父组件中访问。]
P.S.2:您实际上调用了handleChange
而不是将其绑定到构造函数中。
您只需要远程this.handleChange = this.handleChange(this);
绑定。
在构造函数中,您未正确绑定您的函数