在React中绑定this作用域并传参的解决方法

发布时间:2020-08-19 10:09:33 作者:小新
来源:亿速云 阅读:298

这篇文章给大家分享的是有关在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/>
      <h4>{this.state.msg}</h4>
    </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/>
      <h4>{this.state.msg}</h4>
    </div>
  }

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

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

render() { 
  return <div>
    <input type="button" value="Way1" onClick={this.changeMsg1.bind(this,"壹","贰")}/>
    <hr/>
    <h4>{this.state.msg}</h4>
  </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/>
      <h4>{this.state.msg}</h4>
    </div>
  }

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

方式三:使用箭头函数

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

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

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

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

感谢各位的阅读!关于在React中绑定this作用域并传参的解决方法就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. react如何优雅的绑定事件,并且可以优雅的传参
  2. ASP.NET MVC中如何传参并绑定数据

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

react 绑定 this

上一篇:Java获取jar包以外资源的方法

下一篇:javascript实现移动端上传图片功能的方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》