【发布时间】:2020-08-13 03:42:22
【问题描述】:
我目前正在学习 reactJS,我发现很难理解为什么 reactjs 中的箭头函数有时被视为组件,有时被视为普通箭头函数。
在这个例子中:
class CommentListContainer extends React.Component {
state = { comments : [] };
componentDidMount() {
fetchSomeComments(s => // 1- here fetchSomeComments is treated as a normal arrow function
this.setState({ comments: s }));
}
render() {
return <CommentList comments={this.state.comments} />; // 2- here CommentList is treated as a component
}
}
// 1
const fetchSomeComments = cb =>
cb([
{ author: "Chan", body: "You look nice today." },
{ author: "You", body: "I know, right?!" }
]);
// 2
const CommentList = comments =>
<ul>
{
comments.comments.map(
(c, index) => (
<li key = {index}>{c.body}—{c.author}</li>
)
)
}
</ul>
我想了解这一点,如果 CommentList 是一个组件,如何将其编写为具有构造函数(props)的类?
【问题讨论】:
-
React 有 2 种类型的组件,Class 组件和 Functional 组件。所以箭头函数属于功能组件。
-
箭头函数是一种 javascript 语法,React 允许函数式组件这一事实意味着您可以使用箭头函数语法来定义它们。
-
是的,我明白了,现在我发现很难将它转换为类组件,因为我不知道如何使用构造函数(props)解析 cmets,你能推荐我有什么要真正理解它是如何工作的,谢谢。
标签: javascript reactjs ecmascript-6 arrow-functions