2 回答

TA貢獻1804條經(jīng)驗 獲得超7個贊
ReactJS 中的箭頭函數(shù)被認為是一個函數(shù)組件或只是一個箭頭函數(shù),具體取決于它們返回的內(nèi)容。
const CommentList = comments =>
<ul>
{
comments.comments.map(
(c, index) => (
<li key = {index}>{c.body}—{c.author}</li>
)
)
}
</ul>
上述組件稱為無狀態(tài)組件。它除了渲染道具什么都不做。沒有狀態(tài),鉤子等。
但是可以有狀態(tài)的組件是通過react hooks實現(xiàn)的。也就是說,功能組件可以做類組件所做的一切。它可以渲染狀態(tài)執(zhí)行操作,而不僅僅是返回 JSX(就像一個無狀態(tài)組件)
要詳細了解這一點,請查看React Function Component
要使 CommentList 成為類組件,可以執(zhí)行以下操作:
class CommentList extends React.Component {
constructor(props) {
super(props);
}
render () {
/* destructuring props so that we can use "comments" prop directly instead of
using this.props.comments */
const {comments}=this.props;
return (
<ul>
{comments.comments.map((c, index) => (
<li key={index}>
{c.body}—{c.author}
</li>
))}
</ul>
);
}
}
TLDR;普通箭頭函數(shù)和函數(shù)式組件的區(qū)別在于返回類型,即函數(shù)式組件返回 JSX。

TA貢獻1803條經(jīng)驗 獲得超3個贊
class CommentList extends React.Component {
construct(props) {
super(props);
}
render() {
let list_items = [];
for(let c of this.props.comments) {
list_items.push(<li key = {index}>{c.body}—{c.author}</li>);
}
return (
<ul>{list_items}</ul>
);
}
}
function CommentList(props) {
let list_items = [];
for(let c of props.comments) {
list_items.push(<li key = {index}>{c.body}—{c.author}</li>);
}
return (<ul>{list_items}</ul>);
}
在 React 中它們是一樣的,第二個稱為“函數(shù)組件”。
添加回答
舉報