[英]What is the difference between rendering from a JSX and from a function?
考慮以下:
const Foo = ({ bar }) => {
return (
<div>
{bar}
</div>
)
}
<Foo bar='something' />
和Foo({ bar: 'something' })
有什么區別?
render (
<>
{/* Is there any difference for the following two? */}
<Foo bar='something' />
{Foo({ bar: 'something' })}
</>
);
當您調用Foo({ bar: 'something' })
並在組件中渲染結果時,您實際上不再將Foo
視為它自己的 React 組件,而是將其同化到調用組件中。 實際上,這與將調用 function 的結果內聯到父組件中相同。
另一方面,當您在 JSX 語法中使用<Foo>
或等效的React.createElement(Foo)
時, Foo
被視為自己的組件,這意味着它可以利用 React Hooks 等功能。
在您展示的最簡單的情況下,實際上沒有區別,但在實踐中,使用 JSX 語法通常是有意義的。
這期望 foo function 將返回一個 UI(例如 Card、div)。
<Foo bar ='something'/>
這並不期望 foo function 返回 UI,僅在其中運行 FUNCTION。
<Foo({bar:'something'})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.