React中绑定this并传参的几种方式

  • 1. 在 事件处理函数中,直接使用 bind 绑定 this 并传参 
  • 2. 在构造函数中绑定并传参
  • 3. 利用箭头函数的this指向解决

bind的作用:为前面的函数,修改函数内部的 this 指向,让 函数内部的this,指向 bind 参数列表中的 第一个参数 

bind 和 call/apply 之间的区别: call/apply 修改完this指向后,会立即调用前面的函数,但是 bind 只是修改this指向,并不会调用

注意: bind 中的第一个参数,是用来修改 this 指向的,第一个参数后面的所有参数,都会当作将来调用 前面函数 时候的参数传递进去

接下来具体看代码:  

第一种方式的代码: 

import React from 'react'

export default class BindThis extends React.Component{
  constructor(props){
    super(props)
    this.state={
      msg:'这是默认的msg'
    }
  }

  render(){
    return <div>

      {/* 方式1:在 事件处理函数中,直接使用 bind 绑定 this 并传参 */}
      <input type="button" value='绑定This并传参的方式' onClick={this.changeMsg1.bind(this, '🐷', '🍕')}/>
    
      <hr/>

      <h3>{this.state.msg}</h3>
    </div>
  }

  changeMsg1(arg1, arg2){
    //注意:这里的方式,是一个普通的方法,因此,在促发的时候,这里的this是undefined
    // console.log(this);
    this.setState({
      msg:'绑定This并传参的方式'+ arg1 + arg2
    }) 
  }
 
}

第二种方式的代码:

import React from 'react'

export default class BindThis extends React.Component{
  constructor(props){
    super(props)
    this.state={
      msg:'这是默认的msg'
    }

    // 绑定 this 并传参的方式2: 在构造函数中绑定并传参
    // 注意,当为一个函数,调用 bind 改变了this指向后,bind 函数调用的结果,有一个返回值,这个值,就是被改变this指向后的函数的引用;
    // 注意: bind 不会修改 原函数的 this 指向
    this.changeMsg2 = this.changeMsg2.bind(this, '🚗', '👫')
  }

  render(){
    return <div>
      <input type="button" value="绑定this并传参的方式2" onClick={this.changeMsg2} />
      <hr/>
      <h3>{this.state.msg}</h3>  
    </div>
  }


  changeMsg2(arg1,arg2){
    //console.log(this)
    // 注意:这里的方式,是一个普通方法,因此,在触发的时候,这里的 this 是 undefined
    this.setState({
      msg: '绑定this并传参的方式2' + arg1 + arg2
    })
  }

}

 

第二种方式需要注意: 当为一个函数,调用 bind 改变了this指向后,bind 函数调用的结果,有一个返回值,这个值,就是被改变this指向后的函数的引用;
            bind 不会修改 原函数的 this 指向

 第三种方式代码: 

import React from 'react'

export default class BindThis extends React.Component{
  constructor(props){
    super(props)
    this.state={
      msg:'这是默认的msg'
    }

  }

  render(){
    return <div>     
      <input type="button" value="绑定this并传参的方式3" onClick={() => { this.changeMsg3('😊', '😘') }} />
     
      <hr/>

      <h3>{this.state.msg}</h3>

    </div>
  }

  changeMsg3 = (arg1,arg2)=>{
    this.setState({
      msg:'绑定this并传参的方式3' + arg1 + arg2
    })
  }
}
<input type="button" value="绑定this并传参的方式3" onClick={this.changeMsg3('😊', '😘') }/>

注意: 根据第三种方式得上面这一小段代码出现bug,由于传参,通过this.changeMsg3(arg1,arg2)直接调用了这个函数,就是在没有点击时已经调用了,本身onclick事件里面放的是函数,而不是函数的调用的结果,如果这样写,在页面就会直接显示结果,解决方式: 就是在onclick事件中放一个箭头函数,在箭头函数内部调用。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值