【问题标题】:Why do we need to use bind() in ReactJS to access this.props or this.state? [duplicate]为什么我们需要在 ReactJS 中使用 bind() 来访问 this.props 或 this.state? [复制]
【发布时间】:2019-11-11 06:20:52
【问题描述】:

以这段代码为例

   import React, { Component } from ‘react’;
    class App extends Component {
      constructor(props) {
        super(props);
        this.clickFunction = this.clickFunction.bind(this);
      }
      clickFunction() {
        console.log(this.props.value);
      }
      render() {
        return(
          <div onClick={this.clickFunction}>Click Me!</div>
        );
      }
    }

bind(this) 的目的是什么?它将函数 clickFunction 绑定到 clickFunction 已经绑定到的对象的上下文,让我用普通的 javascript 代码说明我想说的话:

class my_class {
  constructor() {
    this.run = this.run.bind(this)
  }
  run() {
    console.log(this.data)
  }
}
my_class.data = 'this is data'
new my_class().run() //outputs 'undefined'

如果你删除了 bind(this) 它会给你同样的结果

  constructor() {
    this.run = this.run
  }

结果:

new my_class().run() //still outputs 'undefined'

我确定我理解错了,这可能是地球上最糟糕的问题,但是我是 es6 的新手,我还不习惯上课,所以我为此道歉

【问题讨论】:

  • 你应该在提问之前做一些研究。这是一个有据可查的事情。 React 类不会在自定义函数上绑定 this 上下文。所以你必须自己绑定它。这是一个更普通的 JS 东西,而不是特定的反应。

标签: javascript reactjs


【解决方案1】:

责怪 JavaScript 而不是 React。这样做是为了在要传递函数时保留对象实例。当然,函数期望这样的对象在语义上必须是正确的。最常见的情况是在传递对象方法时绑定 this。关键字 这取决于函数的调用方式,而不是它的创建方式/位置。与 This 的关系应在调用时保持。

考虑:

class Welcome extends React.Component {
    render() {
      return <button onClick={this.sayName}>Say My 
           Name</button>;                        
    }

    sayName() {
      alert(this.props.name);
    }
}

在 React 中,您可以这样调用: .这会呈现一个按钮。单击该按钮应触发带有“Bob”的警报。

除非它没有。因为在上面的例子中,这在 sayName 函数中是未定义的。

render 函数内部发生的事情是 this 引用了我们的 React 组件的当前实例。该组件定义了一个 sayName 函数,所以 this.sayName 指向我们的函数,很好,花花公子。

但是 React 在幕后所做的是将 this.sayName 分配给另一个变量。也就是说,就是这样:

let onClick = this.sayName;
onClick(); // Technically a click event is passed 
to onClick

// 但这对我们的目的无关紧要 我们得到一个错误。因为这是未定义的。这是 额外的混乱,因为在以前的 React 版本中,React 会为你“自动绑定”事件处理程序,所以它可以工作。但在某个时候,Facebook 决定停止这样做,所以......我们来了。

那么我们如何修复我们的组件呢?我们只是绑定自己,像这样:

<button onClick={this.sayName.bind(this)}>Say My 
Name</button>;

或者使用 ES6 语法:

<button onClick={() => this.sayName()}>Say My 
Name</button>;

它应该可以工作!

【讨论】:

  • 最好在构造函数中绑定或使用箭头函数“自动绑定”this。您的实现将为每个渲染创建一个新函数。
  • 终于有人懂我了,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2018-04-04
  • 2015-08-27
  • 1970-01-01
  • 2021-06-16
  • 2012-10-01
  • 2013-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多