【发布时间】: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