杰网资源 Design By www.escxy.com

在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
  })
}

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

标签:
React绑定this作用域,React绑定this传参,react绑定this并传参

杰网资源 Design By www.escxy.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
杰网资源 Design By www.escxy.com

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。