在 ReactComponent.render() 方法中绑定(this)

IT技术 reactjs
2021-05-23 07:18:15

我有一个相当大的构造函数中React.Component有十多个bind(this)调用。

我认为.bind(this)构造函数对理解我的代码没有任何帮助,尤其是在阅读 render() 内部的代码时。

所以,我想出了以下想法,但是,没有找到如何实现这一点。

render() {
    if (this.methodToBind.getThis() === this) {
        this.methodToBind = this.methodToBind.bind(this);
    }
}

  1. 有什么可能的方法可以获得这个方法(getThis()从上面的例子中)?

  2. 如果上述情况是,那么这样做是否是一个好习惯?

3个回答

而不是这样做,

constructor () {
  super();
  this.myFunc = this.myFunc.bind(this);
}

myFunc () {
  // code here
}

你可以做这样的事情。

constructor () {
  super();
  // leave the binding, it's just not what the cool kids do these days
}

myFunc = () => {
  // see what I did here with = () => {} 
  // this will bind your `this` with it's parent 
  // lexical context, which is your class itself, cool right. Do this!
}

有关参考,请查看箭头函数的 MDN 文档

在哪里绑定这个?

当你React.js 的基于类的组件创建一个函数时,你必须绑定才能从渲染方法调用它。否则函数将不在作用域内this

有几种方法可以做到这一点。

  1. 永远不要bind this在渲染方法中。this每次重新渲染组件时,在 render 方法中绑定都会导致 React 创建一个新函数。这就是我们最常在构造函数中绑定的原因。

  2. 在构造函数中绑定。通过在构造函数中绑定,您可以使用this.FunctionName();

示例绑定这个

    Class MyClass extends Component {

    constructor(props) {
        super(props);
      this.FunctionName = this.FunctionName.bind(this);
    }

   myFunc () {
    // code here 
   }

    render() {
       this.FunctionName();
      return(
       <div>
        ...
       </div>
    );
    }
    }
  1. 用户胖箭头函数而不是传统的函数定义。粗箭头函数在词法上绑定this值。所以在类中使用粗箭头函数时,不必在构造函数中添加bind。

重要- 在 React 类中并不总是可以使用胖箭头函数。取决于你如何设置 React。你可能需要安装,

babel-plugin-transform-class-properties

然后.bablerc像这样将其添加到您的文件中,

{
  "plugins": [
    "transform-class-properties"
  ],
  "presets": [
    "react"
  ]
}

示例胖箭头

 Class MyClass extends Component {

   myFunc = () => {
    // code here
   }

    render() {
       this.FunctionName();
      return(
       <div>
        ...
       </div>
    );
    }
    }

概括

  • 永远不要在渲染中绑定函数。
  • 使用传统函数时总是在构造函数中绑定
  • 这个用脂肪箭头功能时,在功能自动可用。

不确定。

我通常做这样的事情:

onClick={this.handleClick.bind(this)}

或者:

onClick={e => this.handleClick(e)}