gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:59:12 25 4
gpt4 key购买 nike

通常你必须在你的模板中放置一个根元素,比如<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>

最佳答案

你可以返回一个 fragment从您的顶级组件而不是顶级元素:

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>

关于reactjs - 有没有办法避免在 React 中有两个 "root"元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69209510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com