以下哪种方法最适合条件事件处理程序?

时间:2018-11-06 01:51:39

标签: javascript reactjs ecmascript-6

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

方法1 -在构造函数中将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,并在render方法中传递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>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

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

  1. 如果选择方法1 ,则会(有条件地)在内存中节省空间 ,因为在以下情况下,this.handleClick的值很小props.onClickundefinedfalse在第二种方法中,您将始终设置需要占用更多空间的函数(但是,该空间对于我)。

  2. 方法2 更常用,人们通常在没有任何条件的情况下将函数绑定到构造函数中,并在需要的属性中验证调用。

请注意,您可以使用第三种方法来使用onClick道具中的define an arrow function,我并没有真正使用它,只是想提一下

您可以了解有关passing functions to components in react docs

的更多信息