简体   繁体   English

重构函数作为属性从es5传递到es6

[英]Refactoring functions passed as properties from es5 to es6

I am currently in the process of refactoring my code from es5 to es6, but have hit a wall when it came to refactoring... 我目前正在将我的代码从es5重构到es6,但是在重构时遇到了麻烦……

<li className="pure-menu-item" onClick={this.props.onClick}></li>

How would I bind this function which is passed when the component is created, in the constructor? 如何在构造函数中绑定创建组件时传递的此函数?

class NavButton extends React.Component {
  constructor () {
    super();
    this._handleClick = this.props.onClick.bind(this);
  }
  render() {
    return (
      <li className="pure-menu-item" onClick={this.props.onClick}>
        <a className="pure-menu-link">{this.props.text}</a>
      </li>
    );
  }
  _handleClick() {
    alert('test');
  }
}

You're making a _handleClick method on your class, but then overwriting it in the constructor with this._handleClick = this.props.onClick.bind(this); 您正在类上创建_handleClick方法,但随后在构造函数中使用this._handleClick = this.props.onClick.bind(this);覆盖它this._handleClick = this.props.onClick.bind(this); , and then ignoring it completely by passing onClick={this.props.onClick} . ,然后通过传递onClick={this.props.onClick}完全忽略它。

I suspect what you really want is to bind your onClick function to the component that owns it in that component's constructor, rather than in the component it's being passed through. 我怀疑您真正想要的是bind onClick函数bind到在该组件的构造函数中拥有它的组件,而不是在正在通过的组件中进行bind

Will this solve your issue? 这样可以解决您的问题吗?

class NavButton extends React.Component {
  render() {
    return (
      <li className="pure-menu-item" onClick={this.props.handleClick}>
        <a className="pure-menu-link">{this.props.text}</a>
      </li>
    );
  }
}

NavButton.propTypes = {
  handleClick: React.PropTypes.func,
  text: React.PropTypes.string
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM