有没有办法避免在 React 中有两个"root"元素?



通常您必须在模板中放置一个根元素,例如<div id="root"></div>。然后使用React/jsx,将组件(及其子组件)呈现到root中。该组件(当渲染时)可能看起来像这样的<div id="main-wrapper">。最终的渲染将有两个根,一个称为root,一个称为main-wrapper。是否有一种更干净的方式来渲染React?

而不是:

<div id="root">
<div id="main-wrapper>
<section></section>
<section></section>
. . .
</div>
</div>

我可以这样做吗?

<div id="root">
<section></section>
<section></section>
. . .
</div>

您可以从顶层组件返回片段,而不是顶层元素:

const App = () => {
return <>
<section>stuff</section>
<section>goes</section>
<section>here</section>
</>;
};

:

const App = () => {
return <div id="main-wrapper">
<section>stuff</section>
<section>goes</section>
<section>here</section>
</div>;
};
ReactDOM.render(<App/>, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

:后

// Stack overflow's Stack Snippets Babel is so massively out of date that I have to use
// <React.Fragment>...</React.Fragment> rather than <>...</>, but that's just for the
// on-site snippet.
const App = () => {
return <React.Fragment>
<section>stuff</section>
<section>goes</section>
<section>here</section>
</React.Fragment>;
};
ReactDOM.render(<App/>, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

最新更新