react常见的几种事件声明
第一种方式:箭头函数声明
import React from 'react';
class Login extends React.Component {
constructor() {
super();
this.state = {}
}
//箭头函数方式
onFinish = values => {
console.log('Success:', values);
};
onFinishFailed = errorInfo => {
console.log('Failed:', errorInfo);
};
render() {
return <div>
<div className="but1"
onFinish={onFinish} onFinishFailed={onFinishFailed}>点击</div>
<div className="but2"
onFinish={()=>this.onFinish} >点击</div>
</div>
}
}
第二种方式:构造函数中声明
import React from 'react';
class Login extends React.Component {
constructor() {
super();
this.state = {};
this.onFinish=this.onFinish.bind(this);
}
onFinish(){
console.log('点击了')
}
render() {
return <div className="login" onFinish={this.onFinish}></div>
}
}
第三种:bind()绑定
import React from 'react';
class Login extends React.Component {
constructor() {
super();
this.state = {};
}
onFinish(){
event.preventDefault() // 阻止默认行为
event.stopPropagation() // 阻止冒泡
console.log('点击了')
}
render() {
return <div className="login" onFinish={this.onFinish.bind(this)}></div>
}
}
react事件传参数
react事件传参主要有两种方式:bind和es6箭头函数
第一种:
通过 bind 方法来绑定参数,第一个参数指向 this,第二个参数开始才是事件函数接收到的参数:
<button onClick={this.handleClick.bind(this, props0, props1, …}>
handleClick(porps0, props1, …, event) {
// your code here
}
事件:this.handleclick.bind(this,要传的参数)
函数:handleclick(传过来的参数,event)
第二种通过es6进行传参
import React from "react";
class Toggle extends React.Component{
constructor(props){
super(props);
this.state={}
this.handleClick=this.handleClick.bind(this)
}
/**参数传值 *///事件对象e要放在最后
handleClick3(item,e){
e.preventDefault();
console.log('传参1:',item,e)
}
handleClick4(item,e){
e.preventDefault();
console.log('传参2',item,e)
}
render(){
return(
<div>
<button onClick={this.handleClick3.bind(this,'你好')}>
<button onClick={(e)=>this.handleClick4('你好',e)}>第二种事件传参</button>
</div>
)
}
}
export default Toggle;