返回 React.Fragment 或数组有什么区别?
What is the difference between returning React.Fragment or an array?
return和React.Fragment
有区别吗
function Foo(){
return (
<>
<div>hey</div>
<div>hey</div>
</>
)
}
或return组件数组
function Bar(){
return (
[
<div>hey</div>,
<div>hey</div>,
]
)
}
?
这里有一个codesandbox例子。
来自 React 文档:https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html
Using array notation has some confusing differences from normal
JSX:
Children in an array must be separated by commas.
Children in an array must have a key to prevent React’s key warning.
Strings must be wrapped in quotes.
所以,如果你想使用你的第二个例子,你需要给每个项目一个 key
属性,如果你使用 [=11],你必须确保用逗号分隔你的项目列表=].
所以,Fragments
只是给出一个比数组更熟悉的语法
return和React.Fragment
function Foo(){
return (
<>
<div>hey</div>
<div>hey</div>
</>
)
}
或return组件数组
function Bar(){
return (
[
<div>hey</div>,
<div>hey</div>,
]
)
}
?
这里有一个codesandbox例子。
来自 React 文档:https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html
Using array notation has some confusing differences from normal JSX:
Children in an array must be separated by commas.
Children in an array must have a key to prevent React’s key warning.
Strings must be wrapped in quotes.
所以,如果你想使用你的第二个例子,你需要给每个项目一个 key
属性,如果你使用 [=11],你必须确保用逗号分隔你的项目列表=].
所以,Fragments
只是给出一个比数组更熟悉的语法