[英]Why should I specify a wrap element: <div> or <React.Fragment> or <> in JSX returns?
I see React raises errors when returning JSX codes for multiple elements, so it requires to always wrap those elements using these 3 options:我看到 React 在返回多个元素的 JSX 代码时会引发错误,因此它需要始终使用以下 3 个选项包装这些元素:
<>
<React.Fragment>
<div>
eg this one works:例如这个有效:
const myReactComponent = () => {
return (
<div>
<div>Div 1</div>
<div>Div 2</div>
</div>
)
}
instead of:代替:
const myReactComponent = () => {
return (
<div>Div 1</div>
<div>Div 2</div>
)
}
JSX is compiled down to React.createElement()
. JSX 被编译成
React.createElement()
。
<div>Test</div>
is equivalent to相当于
React.createElement('div', 'Test');
Since React.createElement()
only creates a single element which is required by the component, JSX expressions must have one element.由于
React.createElement()
仅创建组件所需的单个元素,因此 JSX 表达式必须具有一个元素。
A common pattern in React is for a component to return multiple elements.
React 中的一个常见模式是组件返回多个元素。 Fragments let you group a list of children without adding extra nodes to the DOM.
片段让您可以对子列表进行分组,而无需向 DOM 添加额外的节点。
Which means React expects a single root element like a single <div></div>
这意味着 React 需要单个根元素,例如单个
<div></div>
Now if you use multiple <div></div>
this is not actually expected by React, to eliminate this problem React introduces <React.Fragment></React.Fragment>
or in short form <></>
and this will enable you to group multiple child components within a single <div></div>
that is already decleared in App component on in your parent component.现在,如果你使用多个
<div></div>
这实际上不是 React 所期望的,为了消除这个问题,React 引入了<React.Fragment></React.Fragment>
或简写形式<></>
这将启用您可以将多个子组件分组到单个<div></div>
中,该 <div></div> 已在父组件中的 App 组件中清除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.