【问题标题】:how to pass parameters to a callback method when you have used the constrocer to bind it?使用 constrocer 绑定后,如何将参数传递给回调方法?
【发布时间】:2018-06-16 07:03:50
【问题描述】:

我正在使用以下方式进行回调,因为据说这是最优化/最快的方式:

class Foo extends React.Component {
  constructor() {
    super();
    this._onClick = this._onClick.bind(this);
  }
  render() {
    return (
      <div onClick={this._onClick}>
        Hello!
      </div>
    );
  }
  _onClick() {
    // Do whatever you like, referencing "this" as appropriate
  }
}

但是如果我需要将参数传递给我的_onClick 方法怎么办? 如果我使用.bind(this) 作为道具,我知道该怎么做,但是我上面展示的方式我不知道如何处理。

顺便说一句,我阅读了here 的文章,但它确实适用于我。

【问题讨论】:

  • 你想从哪里将值传递到哪里?只需使用相应的参数调用该函数即可。

标签: reactjs ecmascript-6 react-router


【解决方案1】:

我认为这些文章会澄清很多: article1articles2。您也可以尝试以下实现,它的灵感来自 2 篇文章:

class Foo extends React.Component {
/*
  in your case you need to make the bind under the render call as below
*/

  _onClick() {
    // Do whatever you like, referencing "this" as appropriate
  }

  render() {
    return (
      /*
          this bind here is necessary to precise the params,
          and about the perfermances issues it's very relative to the app composition.
        */
      <div onClick={this._onClick.bind(this /*,var1, var2*/)}>Hello!</div>
    );
  }
}

// a solution for passing properties without
// entring in perfermances issues is to make a small refacto :

class Foo extends React.Component {
  _onClick() {
    // Do whatever you like, referencing "this" as appropriate
  }
  render() {
    return <MyDiv {...this.props} onItemClick={this._onClick}>Hello!</MyDiv>;
  }
}

const MyDiv = React.createClass({
    render() {
      // Don't need a bind here, since it's just calling
      // our own click handler
      return (
        <div onClick={this.handleClick}>Hello!</div>
      );
    },

    handleClick() {
      // Our click handler has access over the this.props,
      // since React.createClass auto bounds this.
      // so it could just pass what it needs along.
      this.props.onItemClick(/*arguments from this.props*/);
    }
  });

【讨论】:

  • hmmm 这样我就再次使用了粗箭头。它不是在每次渲染上都创建了一个全新的功能吗?
  • 我认为这个博客可以帮助你,这是链接:cdb.reacttraining.com/…
  • @farmcommand2,我已经更新了答案,我认为它至少会有所帮助,因为这个话题令人困惑和神秘。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-03
相关资源
最近更新 更多