react事件处理——修改this指向(面试常问)

方式1:通过bind方法进行原地绑定,从而改变this指向
注:bind不会调用函数本身,只是改变函数中的this指向,bind会返回一个新的函数,再任何时候调用bind返回的新函数都是bind绑定号的this指向。

方式2:通过创建箭头函数

方式3:在constructor中提前对事件进行绑定

方式4:将事件调用的写法改为箭头函数的形式

<body>
    <div id="box"></div>
    <script type="text/babel">
    class MyCom extends React.Component{
        constructor(props){
            super(props)
            this.state={
                texta:"1111",
                textb:"2222",
                textc:"3333",
                textd:"4444"
            }
            this.fund=this.fund.bind(this)
        }
        funa(text){
            this.setState({
                texta:"我是a,我被修改"  
            })
            console.log(text)
        }
        funb=()=>{
            this.setState({
                textb:"我是b,我被修改"  
            })
            console.log(this)
        }
        func(text){
            this.setState({
                textc:"我是c,我被修改"  
            })
            console.log(text)
        }
        fund(){
            this.setState({
                textd:"我是d,我被修改"  
            })
            console.log(this)
        }
        render(){
            return(
                <div>
                    {/*bind(this)的意思是修改了这个单击事件的this指向,让这里的this指向MyCom*/}
                    <button onClick={this.funa.bind(this,"我是传递过来的实参a")}>使用bind原地绑定的方式修改this指向</button>
                    <h1>{this.state.texta}</h1>

                    <button onClick={this.funb}>直接创建箭头函数的方式修改this指向</button>
                    <h1>{this.state.textb}</h1>

                    <button onClick={()=>{this.func("我是传递过来的实参c")}}>直接触发回调函数的方式</button>
                    <h1>{this.state.textc}</h1>

                    <button onClick={()=>{this.fund()}}>在constructor中提前对事件进行绑定</button>
                    <h1>{this.state.textd}</h1>
                </div>
            )
        }
    }
    ReactDOM.render(<MyCom/>,document.getElementById("box"))
    </script>
</body>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值