React事件绑定

2019-11-13  本文已影响0人  读心的心
1、在构造函数内使用bind绑定this
import React, { Component } from "react";
class Click extends Component {
    constructor(props){
        super(props)
        this.hanldeClick = this.hanldeClick.bind(this)
    }
   hanldeClick(){
       console.log("构造函数内使用bind绑定this")
   }
    render() {
        return <button onClick={this.hanldeClick} >Click</button>
    }
}


export default Click
2、箭头函数绑定this
import React, { Component } from "react";
class Click extends Component {
   hanldeClick(){
       console.log("箭头函数绑定this")
   }
    render() {
        return <button onClick={()=>this.hanldeClick()} >Click</button>
    }
}


export default Click
3、使用bind()绑定this
import React, { Component } from "react";
class Click extends Component {
   hanldeClick(){
       console.log("bind绑定this")
   }
    render() {
        return <button onClick={this.hanldeClick.bind(this)} >Click</button>
    }
}


export default Click
4、使用箭头函数定义事件,实现绑定this
import React, { Component } from "react";
class Click extends Component {
   hanldeClick=()=>{
       console.log("绑定this")
   }
    render() {
        return <button onClick={this.hanldeClick} >Click</button>
    }
}


export default Click
上一篇 下一篇

猜你喜欢

热点阅读