美文网首页React
React(组件的this绑定)

React(组件的this绑定)

作者: 余生筑 | 来源:发表于2017-10-26 08:36 被阅读8次
  • 在constructor中绑定this
class Epp extends Component {
    constructor()
    {
        super();
        this.fn=this.fn.bind(this);//注意这一步需在constructor()中设置    
    }
    fn(event)
    {
        console.log('123') 
    }

    render() {
        return (
            <div onClick={this.fn}>
            123
            </div>  
            );
        } 
    }
  • 在render中绑定this
class Epp extends Component {
    constructor()
    {
        super();
    }
    fn(event)
    {
        console.log('123') 
    }

    render() {
        return (
            <div onClick={this.fn.bind(this)}>
            123
            </div>  
            );
        } 
    }
  • 箭头函数
class Epp extends Component {
    constructor()
    {
        super();
        this.fn=this.fn.bind(this);     
    }
    fn=(event)=>
    {
        console.log('123') 
    }

    render() {
        return (
            <div onClick={this.fn}>
            123
            </div>  
            );
        } 
    }

相关文章

网友评论

    本文标题:React(组件的this绑定)

    本文链接:https://www.haomeiwen.com/subject/nndhpxtx.html