【发布时间】:2019-05-23 23:48:21
【问题描述】:
我正在学习本教程 this tutorial 他使用这种我觉得很奇怪的组件声明(对于 React 中的新手)
const Story = ({ story, columns, onArchive }) => {
const {
title,
url,
author,
comments,
points,
objectID,
} = story;
return (
<div className="story">
<span style={{ width: columns.title.width }}><a href={url}>{title}</a></span>
<span style={{ width: columns.author.width }}>{author}</span>
<span style={{ width: columns.comments.width }}>{comments}</span>
<span style={{ width: columns.points.width }}>{points}</span>
<span style={{ width: columns.archive.width }}>
<ButtonInline onClick={() => onArchive(objectID)}>Archive</ButtonInline>
</span>
</div>
);
}
基本上他将组件放在一个没有渲染功能的函数中——只是直接返回。
出于好奇,我使用更熟悉的方法重新创建了它:
class Story extends React.Component {
render() {
const {
title,
url,
author,
comments,
points,
objectID,
} = this.props.story;
return(
<div className="story">
<span style={{ width: this.props.columns.title.width }}><a href={url}>{title}</a></span>
<span style={{ width: this.props.columns.author.width }}>{author}</span>
<span style={{ width: this.props.columns.comments.width }}>{comments}</span>
<span style={{ width: this.props.columns.points.width }}>{points}</span>
<span style={{ width: this.props.columns.archive.width }}>
<ButtonInline onClick={() => this.props.onArchive(objectID)}>Archive</ButtonInline>
</span>
</div>);
}
}
它的渲染是一样的。
现在,我想知道以下几点:
以前的实现是否接受状态?如果是这样,如何编写构造函数和状态声明?
是不是比后者更有效率?它看起来确实更简洁明了,但是这种编码风格的优缺点是什么?
它叫什么?我很想了解更多关于这方面的信息。
谢谢!
【问题讨论】:
-
你在这里可能有很多关于这个问题的答案。但我的建议是你阅读 react 官方文档。他们的第一章解释了类组件和功能组件之间的实际区别
-
@AnaLizaPandac 如果您在 SO 上发现类似问题,请将其标记为重复
-
@quirimmo 注意。
标签: javascript reactjs