Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.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
在onClick事件之前在页面加载时调用Reactjs函数_Reactjs_Function_Onclick - Fatal编程技术网

在onClick事件之前在页面加载时调用Reactjs函数

在onClick事件之前在页面加载时调用Reactjs函数,reactjs,function,onclick,Reactjs,Function,Onclick,当页面加载我的代码时,函数工作如下 家长 import React,{Component}来自“React”; 从“/Button”导入ExtnButton; 类MovieList扩展组件{ handleDelete=索引=>{ 控制台日志(“内部handleDelete:”); }; render(){ 返回( ); } } 导出默认电影列表; 儿童 import React,{Component}来自“React”; 类按钮扩展组件{ 状态={}; render(){ 返回( 删除 );

当页面加载我的代码时,函数工作如下
家长

import React,{Component}来自“React”;
从“/Button”导入ExtnButton;
类MovieList扩展组件{
handleDelete=索引=>{
控制台日志(“内部handleDelete:”);
};
render(){
返回(
);
}
}
导出默认电影列表;

儿童

import React,{Component}来自“React”;
类按钮扩展组件{
状态={};
render(){
返回(
删除
);
}
}
导出默认按钮;
但在页面加载函数handleDelete调用时没有任何单击事件,这是错误的:

onClick={this.props.handleDelete(this.props.index)}

正确:

onClick={()=>this.props.handleDelete(this.props.index)}
错误:

onClick={this.props.handleDelete(this.props.index)}

正确:

onClick={()=>this.props.handleDelete(this.props.index)}

这是因为您直接在onClick事件中调用该方法。有三种方法可以使用参数绑定事件:

使用内联箭头函数:

onClick={() => this.props.handleDelete(this.props.index)}
使用公共类方法(正如您目前所做的),但只需要curry:

handleDelete = index => () => {
  console.log("inside handleDelete:");
};
使用边界法:

handleDelete(index) {...}
handleDelete(index) {...}
但为此,需要在构造函数内绑定
this

this.handleDelete = this.handleDelete.bind(this)

如果您需要通过活动:

(using inline arrow function)
onClick={(e) => this.props.handleDelete(this.props.index, e)}
(using public class method)
handleDelete = index => e => {
  console.log(e);
};

请注意,如果使用内联箭头函数,则不需要curry函数。这很好:

handleDelete = index => {...}
或者,不使用公共类方法(即绑定方法):


这是因为您直接在onClick事件中调用该方法。有三种方法可以使用参数绑定事件:

使用内联箭头函数:

onClick={() => this.props.handleDelete(this.props.index)}
使用公共类方法(正如您目前所做的),但只需要curry:

handleDelete = index => () => {
  console.log("inside handleDelete:");
};
使用边界法:

handleDelete(index) {...}
handleDelete(index) {...}
但为此,需要在构造函数内绑定
this

this.handleDelete = this.handleDelete.bind(this)

如果您需要通过活动:

(using inline arrow function)
onClick={(e) => this.props.handleDelete(this.props.index, e)}
(using public class method)
handleDelete = index => e => {
  console.log(e);
};

请注意,如果使用内联箭头函数,则不需要curry函数。这很好:

handleDelete = index => {...}
或者,不使用公共类方法(即绑定方法):

应该是onClick={()=>this.props.handleDelete(this.props.index)}应该是onClick={()=>this.props.handleDelete(this.props.index)}