【问题标题】:In a React Component, where should I bind arguments to my onClick functions?在 React 组件中,我应该在哪里将参数绑定到我的 onClick 函数?
【发布时间】:2017-02-23 22:16:14
【问题描述】:

所以在一个示例组件中 <Button doStuff={doStuff} />

我知道这很糟糕,它会在每次渲染时创建一个新函数:

class Button extends Component {
  const value = getClickValue(this.props); // do something with props 
  render() {
    <button onClick={() => this.props.doStuff(value)}>Click me</button>
  }
}

但不确定以下哪个对性能更好:

1) 在类属性函数中绑定点击值

这是一个微不足道的例子,但是在我当前的组件中,处理 props 的代码使我的组件变得杂乱无章,并且当您想要努力拥有 DUMB 组件和智能容器时,使组件更加智能且不那么愚蠢。

class Button extends Component {
  handleClick = () => {
    const value = getClickValue(this.props); // do something with props to get value
    this.props.doStuff(value);
  }

  render() {
    <button onClick={this.handleClick}>Click me</button>
  }
}

2) 将绑定函数作为 props 从容器发送到无状态功能组件。

从组织的角度来看,这种方法似乎更好。该组件尽可能地愚蠢,只关心渲染。但它会影响性能吗?例如,每次ownProps 更改时都会构造一个新函数吗?

const Button = (onClick) => (
  <button onClick={this.props.onClick}>Click me!</button>
)

import { connect } from 'react-redux';

const mapDispatchToProps = (dispatch, ownProps) => {
  const value = getClickValue(ownProps);
  return {
    onClick: () => doStuff(value)
  };
};

connect(null, mapDispatchToprops)(Button);

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    在您的第二种方法中,每次您的道具更改时,都会调用mapDispatchToProps。由于您要返回一个箭头函数,因此它将再次创建该函数。

    这使您的第一个建议成为最佳选择。

    【讨论】:

      猜你喜欢
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多