【问题标题】:Why does React warn me against binding a component method to the object?为什么 React 会警告我不要将组件方法绑定到对象?
【发布时间】:2015-01-03 09:23:36
【问题描述】:

我这里有这个组件。我想将调用处理程序传递给我创建的每个 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。

【问题讨论】:

  • “调用处理程序”是指事件处理程序吗?事件应该冒泡到父级,并且可以在那里捕获。我错过了什么?
  • 我没有看到那个错误:jsfiddle.net/s6dok0xv.

标签: javascript reactjs


【解决方案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 以找到有问题的行。

【讨论】:

  • 哦,你是对的,它在其他地方。我现在很尴尬
  • @FakeRainBrigand 现在似乎在第二种情况下没有警告,.bind(this, foo)。它适用于.bind(this)。用 react@0.13.1 测试。 jsfiddle.net/69z2wepo/17453 而文档目前显示这样做:facebook.github.io/react/tips/…。这个关于何时在 React 中绑定和何时不绑定的故事似乎过于复杂。
  • .bind(null, 起作用的原因是,自从v0.4 以来,react 自动绑定,通过执行.bind(null,我们必须执行this.methond.bind(this).bind(null, arg1, arg2)。只是想你们中的一些人可能想知道为什么它有效。
【解决方案2】:

这里是更新的文档示例

React.createClass({
  onClick: function(event) {/* do something with this */},
  render: function() {
    return <button onClick={this.onClick} />;
  }
});

Update in ReactJS Docs

【讨论】:

    猜你喜欢
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    相关资源
    最近更新 更多