【发布时间】:2017-10-03 14:05:59
【问题描述】:
我有一个带有箭头函数事件处理程序的功能组件,这被认为是不好的做法,因为每次渲染组件时都需要重新创建函数。
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 组件中导出逻辑并在父容器中执行处理程序逻辑,但这个问题与性能主题有关。
谢谢
【问题讨论】:
-
我觉得这个问题应该在Codereview
标签: javascript reactjs