如何避免React组件自动绑定'this'?

时间:2016-08-04 13:36:51

标签: javascript reactjs

我有这样的功能:

obj = {
  func: function() {
    console.log(this);
  }
}

它作为prop:

传递给React组件
React.createElement(Component, {
  funcAsProp: obj.func
}

然后在这样的反应组件中调用:

let Component = React.createClass({
  displayName: 'Component',

  clickHandler: function () {
    this.props.funcAsProp();
  },

  render: function () {
    return React.createElement('div', {
      onClick: this.clickHandler
    });
  }
});

当像这样调用obj.func这是组件。我仍然对Javascript'this'和React自动绑定有些困惑。上下文是否被React绑定到obj.func,或者这是我在这里找不到的一些基本的Javascript事情?

如果是关于自动绑定,如何调用该函数而不绑定它?

3 个答案:

答案 0 :(得分:1)

当你执行funcAsProp: obj.func时,你失去了背景。现在,您funcAsProp等于func,并且不再有关于obj的信息。试试这个:

React.createElement(Component, {
  funcAsProp: obj
}

并在处理程序中:

this.props.funcAsProp.func();

或者您可以绑定您的上下文:

React.createElement(Component, {
  funcAsProp: obj.func.bind(obj)
}

答案 1 :(得分:1)

您可以在将this传递给道具之前设置obj.func,因为func丢失了自己的上下文并使用了React的组件上下文



const obj = {
  name: 'obj, name',
  
  func: function () {
    console.log(this.name);
  }
};

let Component = React.createClass({
  displayName: 'Component',

  clickHandler: function () {
    this.props.funcAsProp();
  },

  render: function () {
    return React.createElement('div', {
      onClick: this.clickHandler
    }, 'Click');
  }
});

ReactDOM.render(
  React.createElement(Component, { funcAsProp: obj.func.bind(obj) }),
  document.getElementById('container')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

this将是函数调用的上下文,因此在这种情况下它将是Component。这是Javascript默认行为,如果您希望将function绑定到原始上下文,则在声明时需要执行以下操作:

obj = {
  func: function() {
    console.log(this);
  }.bind(this);
} 

或将函数传递给组件时:

React.createElement(Component, {   funcAsProp: obj.func.bind(this) }