首页 文章

带有箭头函数处理函数的函数组件对于性能更好,那么一个类组件在构造函数中绑定了一个处理程序

提问于
浏览
1

我有一个带箭头函数事件处理程序的函数组件,由于需要在每次呈现组件时重新创建函数,这被认为是不好的做法 .

const SimpleQuestion = ({
  question,
  onChangeQuestionTitle
}) => {

  return (
    <div>
      <input
        type="text"
        placeholder="Enter Question"
        value={question.title}
        onChange={(e) => onChangeQuestionTitle({
          id: question.id,
          title: e.target.value
        })}
      />
    </div>
  );
};

我不能为它定义外部函数,因为它需要访问props,我也看不到这个例子中的任何优点:

const SimpleQuestion = ({
  question,
  onChangeQuestionTitle
}) => {

  const handleChangeQuestionTitle = (e) => {
    onChangeQuestionTitle({
      id: question.id,
      title: e.target.value
    });
  };

  return (
    <div>
      <input
        type="text"
        placeholder="Enter Question"
        value={question.title}
        onChange={handleChangeQuestionTitle}
      />
    </div>
  );
};

为了消除对箭头函数的需要,我可以使用带有构造函数和bind()的类组件 . 例如:

class SimpleQuestion extends React.Component {
  constructor(...args) {
    super(...args)  
    this.onChangeQuestionTitle = this.onChangeQuestionTitle.bind(this);
  }

  render() {
    return (
      <div>
        <input
          type="text"
          placeholder="Enter Question"
          value={question.title}
          onChange={this.onChangeQuestionTitle}
        />
      </div>
    );
  }

  onChangeQuestionTitle(e) {
    this.props.onChangeQuestionTitle({
      id: question.id,
      title: e.target.value
    });
  }
}

我应该使用带箭头功能的类组件或功能组件吗?从性能角度来看哪个更好?

PS:我知道我可以从Question组件导出逻辑并在父容器中执行处理程序逻辑,但这个问题与性能主题有关 .

谢谢

2 回答

  • 0

    因为你只需要返回一些jsx并且你不关心组件的状态或任何生命周期方法,最好的选择是#2 .

    关于通过将函数的引用传递给 render() 方法而不是函数本身方法来创建不必要的匿名函数的问题将得到解决 .

  • 0

    第二种或第三种方法都是首选 . 至于你应该选择哪一个,我认为这是个人偏好 . 我个人更喜欢胖箭头语法(#2),因为你不必在构造函数中绑定 . 但无论哪种情况,您都可以通过将对函数(而不是函数定义)的引用传递给render()来解决创建不必要的匿名函数的问题 .

相关问题