小编典典

为什么React会警告我不要将组件方法绑定到对象?

reactjs

我这里有这个组件。我想将调用处理程序传递给我创建的每个listElement。如果我像下面那样使用bind(this),则可以正常运行。问题是我从控制台的React收到此警告:bind(): You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call.

var MyList = React.createClass({
  render: function () {
    var listElements = this.props.myListValues.map(function (val) {
      return (
        <ListElement onCallHandler={this.props.parentsCallHandler} val={val} />
        );
    }.bind(this));
    return (
      <ul>
          {listElements}
      </ul>
      );
  }
});

如果我不绑定它,我的孩子们将不了解呼叫处理程序。我可以做些什么?

PS:

我知道解构作业,如http://facebook.github.io/react/docs/transferring-
props.html#transferring-with-…-in-
jsx所述,但我不想使用Harmony。


阅读 340

收藏
2020-07-22

共1个答案

小编典典

该错误来自代码中的其他地方。当您执行此操作时会收到错误,this.someFunction.bind(something)而某些操作则不会null

this.someFunction.bind({}, foo);    // warning
this.someFunction.bind(this, foo);  // warning, you're doing this
this.someFunction.bind(null, foo);  // okay!

.bind(this在您的代码中进行搜索以查找违规行。

2020-07-22