React事件绑定的方法

React事件绑定的方法

前言

React事件绑定即将事件函数中的this与类实例对象的this绑定。

法一:在构造器中绑定this

export default class Test extends Component {
    
    
    constructor(props){
    
    
        super(props)
        this.handleClick = this.handleClick.bind(this)
    }
 
    handleClick(){
    
    
        console.log('点击了',this)
    }
 
    render(){
    
    
        return (
            <div onClick={
    
     this.handleClick }>click btn</div>
        )
    }
}

法二:使用箭头函数

export default class Test extends Component {
    
    
 
    handleClick=()=>{
    
    
        console.log('点击了',this)
    }
 
    render(){
    
    
        return (
            <div onClick={
    
     this.handleClick }>click btn</div>
        )
    }
}

法三:用箭头函数包裹起来

export default class Test extends Component {
    
    
 
    handleClick(){
    
    
        console.log('点击了',this)
    }
 
    render(){
    
    
        return (
            <div onClick={
    
     ()=> this.handleClick() }>click btn</div>
        )
    }
}

猜你喜欢

转载自blog.csdn.net/wdhxs/article/details/111935975