我有一个带箭头函数事件处理程序的函数组件,由于每次渲染组件时都需要重新创建函数,因此被认为是不好的做法。
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>
);
};
我无法为它定义外部函数,因为它需要访问道具,在这个例子中我也没有看到任何优势:
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组件导出逻辑并在父容器中执行处理程序逻辑,但这个问题与性能主题有关。
由于
答案 0 :(得分:0)
第二种或第三种方法都是首选。至于你应该选择哪种,我认为这是个人偏好。我个人更喜欢胖箭头语法(#2),因为你不必在构造函数中绑定。但无论哪种情况,您都可以通过将对函数(而不是函数定义)的引用传递给render()来解决创建不必要的匿名函数的问题。
答案 1 :(得分:0)
因为你只需要返回一些jsx并且你不关心组件的状态或任何生命周期方法,最好的选择是#2。
关于通过将对函数的引用传递给render()
方法而不是函数本身方法来创建不必要的匿名函数的问题将得到解决。