Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React-onChange事件返回TypeError:props.handleChange不是函数_Javascript_Reactjs_Onchange_Eventhandler - Fatal编程技术网

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

Javascript React-onChange事件返回TypeError:props.handleChange不是函数,javascript,reactjs,onchange,eventhandler,Javascript,Reactjs,Onchange,Eventhandler,我在classApp下创建了一个名为handleChange的简单类方法,参数为id 我试图从名为TodoItem的子函数组件调用此handleChange方法 当我点击复选框时,浏览器返回一个TypeError,表示props.handleChange(props.item.id)不是函数,如图所示: 有人能解释一下我在TodoItem中的代码有什么问题吗 Appclass组件: import React,{Component}来自“React”; 从“/TodoItem”导入TodoIte

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

我试图从名为
TodoItem
的子函数组件调用此
handleChange
方法

当我点击复选框时,浏览器返回一个
TypeError
,表示
props.handleChange(props.item.id)不是函数,如图所示:

有人能解释一下我在
TodoItem
中的代码有什么问题吗

App
class组件:

import React,{Component}来自“React”;
从“/TodoItem”导入TodoItem;
从“/todosData”导入todosData;
类应用程序扩展组件{
构造函数(){
超级();
此.state={
todos:todosData,
};
this.handleChange=this.handleChange(this);
}
手柄更换(id){
控制台日志(“已更改”,id);
}
render(){
const todoItems=this.state.todos.map((项)=>(
));
返回{todoItems};
}
}
导出默认应用程序;
TodoItem
功能组件:

从“React”导入React;
功能待办事项(道具){
返回(
props.handleChange(props.item.id)}
/>
{props.item.text}

); } 将默认值导出到doitem;
您需要在使用时绑定
handleChange
,或者将其转换为箭头函数。我更喜欢箭头函数

绑定

this.handleChange = this.handleChange.bind(this);
箭头函数

handleChange = (id) => {
    console.log("changed", id);
}
注意:如果您不更改子组件中的项,那么将项传递到子组件并将item.id传递到props.handleChange是没有意义的,因为它首先可以在父组件中访问


p.S.2:实际上,您调用了
handleChange
,而不是在构造函数中绑定它。

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

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
}
类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
todos:todosData,
};

this.handleChange=this.handleChange.bind(this)//谢谢你,ilkerkaran,我确实在App.js下的构造函数()中绑定了handleChange,正如你在代码中看到的那样。@user13145130我想你忘了绑定this.handleChange=this.handleChange.bind(this)
非常感谢您指出这个简单的错误。我正在排除故障,但无法发现这个错误。我必须彻底检查我的眼睛。