【问题标题】:Which of these approaches is better for a conditional event handler?这些方法中哪一种更适合条件事件处理程序?
【发布时间】:2019-04-09 10:09:11
【问题描述】:

如果将回调函数传递给组件,我希望我的 Button 组件仅处理 onClick 事件。我有两种方法,但我不知道哪种方法更好。

方法一 - 在构造函数中将handleClickthis.handleClickfalse绑定,并在渲染方法中将handleClick传递给onClick

class Button extends Component {
  static propTypes = {
    children: PropTypes.element.isRequired,
    onClick: PropTypes.func
  };

  static defaultProps = {
    onClick: undefined
  };

  constructor(props) {
    super(props);

    this.handleClick = (props.onClick) && this.handleClick.bind(this);
  }

  handleClick() {
    const { onClick } = this.props;

    onClick();
  }

  render() {
    const { children } = this.props;

    return (
      <Wrapper onClick={this.handleClick}> // False if onClick is undefined
        {children}
      </Wrapper>
    );
  }
}

方法2 - 在构造函数中绑定handleClick,并在渲染方法中传递handleClickfalse

class Button extends Component {
  static propTypes = {
    children: PropTypes.element.isRequired,
    onClick: PropTypes.func
  };

  static defaultProps = {
    onClick: undefined
  };

  constructor() {
    super();

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    const { onClick } = this.props;

    onClick();
  }

  render() {
    const { children, onClick } = this.props;

    return (
      <Wrapper onClick={(onClick) && this.handleClick}>
        {children}
      </Wrapper>
    );
  }
}

【问题讨论】:

    标签: javascript reactjs ecmascript-6


    【解决方案1】:

    我认为这是一个偏好问题,因为这两种情况几乎相同。

    1. 如果您选择方法 1,您将节省内存空间(有条件地),因为对于 @987654324 的情况,this.handleClick 将是一个很小的值@ 是 undefinedfalse在第二种方法中,您总是会设置占用更多空间的函数(但是,这个空间对我来说是贬值的)。

    2. 方法2比较常用,人们通常在构造函数中不加任何条件地绑定函数,并在需要的属性中验证调用。

    顺便说一句,您可以使用第三种方法,即在onClick 属性中使用define an arrow function,我并没有真正使用这个方法,只是想提一下。

    您可以了解更多关于passing functions to components in react docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      • 2012-02-08
      相关资源
      最近更新 更多