详解三种方式在React中解决绑定this的作用域问题并传参

在React中时常会遇到this指向的作用域问题 从而导致undefined报错

先来个Demo:
功能很简单 点击按钮改变文字

import React from \'react\';

export default class BindWithThis extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      msg:\"BindWithThis\"
    }
  }

  render() { 
    return <div>
      <input type=\"button\" value=\"Way1\" onClick={this.changeMsg1}/>
      <hr/>
      <h3>{this.state.msg}</h3>
    </div>
  }

  changeMsg1(){
    console.log(this)
    this.setState({
      msg:\"Way1\"
    })
  }
}

但会遇到问题:Cannot read property ‘setState\’ of undefined

详解三种方式在React中解决绑定this的作用域问题并传参

这是因为 在changeMsg1方法内部的this指向的并不是外面的组件 因而根本就不会有setState()方法了 自然会报错

为此 有三种解决方法

方式一:在事件处理函数中使用.bind()

只要这样即可:

render() { 
    return <div>
      <input type=\"button\" value=\"Way1\" onClick={this.changeMsg1.bind(this)}/>
      <hr/>
      <h3>{this.state.msg}</h3>
    </div>
  }

bind()的作用是为前面的函数修改函数内部的this的指向 从而使得函数内部的this指向bind中的第一个参数

bind()还可以传值:
bind第一个参数后面的所有参数都会作为调用bind前面的函数的参数传递

render() { 
  return <div>
    <input type=\"button\" value=\"Way1\" onClick={this.changeMsg1.bind(this,\"壹\",\"贰\")}/>
    <hr/>
    <h3>{this.state.msg}</h3>
  </div>
}

changeMsg1(arg1,arg2){
  this.setState({
    msg:\"Way1\"+arg1+arg2
  })
}

除了bind()之外 还有call()和apply() 它们都能改变函数内部的this的指向
不过bind()和call()/apply()的区别是:bind()并不会立即调用 而call()/apply()会立即调用

方式二:在构造函数中使用.bind()

当为一个函数调用bind 从而改变this的指向之后 bind函数的返回值是这个被改变this指向的函数的改变后的引用
bind并不会修改原函数的this的指向 而是返回一个修改后的函数的指向 因此需要重新接收方可生效

import React from \'react\';

export default class BindWithThis extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      msg:\"BindWithThis\"
    }

    // 当为一个函数调用bind 改变this的指向之后 bind函数的返回值是这个被改变this指向的函数的改变后的引用 因此需要重新接收
    this.changeMsg2 = this.changeMsg2.bind(this,\"壹\",\"贰\")
  }

  render() { 
    return <div>
      <input type=\"button\" value=\"Way2\" onClick={this.changeMsg2}/>
      <hr/>
      <h3>{this.state.msg}</h3>
    </div>
  }

  changeMsg2(arg1,arg2){
    this.setState({
      msg:\"Way2\"+arg1+arg2
    })
  }
}

方式三:使用箭头函数

利用了箭头函数的特性:箭头函数内部的this永远指向调用者方的this

render() { 
  return <div>
    <input type=\"button\" value=\"Way3\" onClick={() => {this.changeMsg3(\"壹\",\"贰\")}}/>
    <hr/>
    <h3>{this.state.msg}</h3>
  </div>
}

changeMsg3 = (arg1,arg2) => {
  this.setState({
    msg:\"Way3\"+arg1+arg2
  })
}

当然 更推荐使用更加方便的箭头函数

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容