为什么React警告我不要将组件方法绑定到对象? [英] Why does React warn me against binding a component method to the object?

查看:109
本文介绍了为什么React警告我不要将组件方法绑定到对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个组件。我想向我创建的每个listElement传递一个调用处理程序。如果我这样做,使用 bind(this),它可以正常工作。问题是我在控制台中从React收到此警告: bind():您正在将组件方法绑定到组件。 React会以高性能方式自动为您执行此操作,因此您可以安全地删除此调用。

I have this here component. I want to pass down a call handler to each listElement I create. If I do it like below, with bind(this), it works properly. The problem is that I get this warning from React in the console: 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>
      );
  }
});

如果我不绑定它,我的孩子们不知道呼叫处理程序。我可以做些什么不同的事情?

If I don't bind it, my children don't know about the call handler. What could I have done differently?

PS:

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

I know about destructuring assignments, like explained http://facebook.github.io/react/docs/transferring-props.html#transferring-with-...-in-jsx, but I don't want to use Harmony.

推荐答案

错误来自代码中的其他位置。当您执行 this.someFunction.bind(某事物)并且某些内容不是 null 时,您会收到错误。

The error is coming from somewhere else in the code. You get the error when you do this.someFunction.bind(something) and something isn't null.

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

搜索 .bind(此在你的代码中找到有问题的行。

Do a search for .bind(this in your code to find the offending line.

这篇关于为什么React警告我不要将组件方法绑定到对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆