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



我在其构造函数中有一个很大的React.Component,有十个以上的bind(this)调用。

我认为构造函数中的.bind(this)没有提供任何帮助以理解我的代码,尤其是在读取Render内部的代码((。

所以,我想出了以下想法,但是,找不到如何实现这一目标。

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

  1. 有什么可能的方法可以得到方法(上面的示例中的getThis()(?

  2. 如果是的,那么这样做是一个好习惯吗?

而不是这样做,

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 中基于A 类中创建一个函数时,您必须绑定this才能从渲染方法中调用它。否则该功能将不会在范围中。

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

  1. 在渲染方法中切勿bind this。渲染方法中的binding this将导致REACT每次启动组件时都会创建一个新功能。这就是为什么我们最常在构造函数中绑定的原因。

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

  3. 在渲染方法中调用您的功能

示例绑定以下

    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值。因此,当您在类中使用Fat Arrow功能时,您不必添加构造函数中的功能。

重要的 - 脂肪箭头功能并不总是可在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)}

最新更新