JSX 表达式在 React 中必须有一个父元素
JSX expressions must have one parent element in React
当组件返回多个元素时,出现 React.js 错误“JSX 表达式必须有一个父元素”。
要解决该错误,请将元素包装在父div
元素中或使用片段。
下面是错误如何发生的示例。
export default function App() { // ⛔️ JSX expressions must have one parent element. return ( <h2>One</h2> <h2>Two</h2> ); }
上面示例中的问题是App
组件返回多个元素。
使用 React Fragment 解决错误
解决错误的一种方法是使用
React fragment。
export default function App() { return ( <> <h2>One</h2> <h2>Two</h2> </> ); }
当我们需要在不向 DOM 添加额外节点的情况下对子列表进行分组时,会使用片段。
您可能还会看到使用了更冗长的片段语法。
import React from 'react'; export default function App() { return ( <React.Fragment> <h2>One</h2> <h2>Two</h2> </React.Fragment> ); }
上面的两个示例实现了相同的结果——它们对子元素列表进行分组,而不向 DOM 添加额外的节点。
将你的组件包装在另一个 DOM 元素中
另一种解决方案是将您的子元素包装在另一个 DOM 元素中,例如div
.
export default function App() { return ( <div> <h2>One</h2> <h2>Two</h2> </div> ); }
这解决了错误,因为我们现在返回一个div
包含多个子元素的单个元素,而不是返回多个元素。
div
doesn’t break your layout, otherwise use a fragment, because fragments don’t add any extra markup to the DOM.# The error also occurs in conditionals
You might also see the error occur in conditionals if one of the code paths
returns multiple elements at the same level.
export default function App() { return ( <div> {/* ⛔️ JSX expressions must have one parent element.ts(2657) */} {true ? ( <h2>One</h2> <h2>Two</h2> ) : null} </div> ); }
The truthy path of the ternary operator returns 2 elements at the same level,
which caused the error. We can get around this by wrapping the two elements with
a fragment.
export default function App() { return ( <div> {true ? ( <> <h2>One</h2> <h2>Two</h2> </> ) : null} </div> ); }
Now each code path of the ternary returns a single value.
# React components are just functions
React components are just functions, so when we return multiple elements at the
same level, we are effectively using multiple return statements at the same
level of a function.
function render() { return React.createElement('h2', null, 'One'); return React.createElement('h2', null, 'Two'); }
The second return
statement is unreachable and this is invalid syntax.
# Returning multiple elements in an array
An alternative approach that you might see is to group the elements into an
array.
export default function App() { return [<h2 key={0}>One</h2>, <h2 key={1}>Two</h2>]; }
The array is a single value, so the error is resolved, however, we are required
to pass a
unique key
prop to
each array element.
This is unnecessary and should be avoided as the fragment syntax is much more
readable and intuitive.
export default function App() { return ( <> <h2>One</h2> <h2>Two</h2> </> ); }