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

and*_*sem 14 javascript 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>
      );
  }
});
Run Code Online (Sandbox Code Playgroud)

如果我不绑定它,我的孩子们不知道调用处理程序.我能做些什么不同的事情?

PS:

我知道解构分配,比如解释http://facebook.github.io/react/docs/transferring-props.html#transferring-with-...-in-jsx,但我不想使用Harmony.

Bri*_*and 31

错误来自代码中的其他位置.当你做你的错误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!
Run Code Online (Sandbox Code Playgroud)

.bind(this在您的代码中搜索以查找有问题的行.

  • @FakeRainBrigand似乎它现在没有在第二种情况下警告,`.bind(this,foo)`.它与`.bind(this)`有关.用react@0.13.1测试.https://jsfiddle.net/69z2wepo/17453/当前的文档显示了这样做:https://facebook.github.io/react/tips/communicate-between-components.html.关于何时绑定以及何时不在React中的这个故事似乎过于复杂. (3认同)
  • 之所以`.bind(null,`的工作原理是这样的,因为自[v0.4]起反应自动引发(http://facebook.github.io/react/blog/2013/07/02/react-v0-4-) autobind-by-default.html),通过`.bind(null`,我们必须执行`this.methond.bind(this).bind(null,arg1,arg2)`.只是觉得有些人可能想要知道**为什么**它有效. (3认同)