react常見幾種事件宣告

梧桐芊羽發表於2020-10-14

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;

相關文章