reactjs - 有没有办法避免在 React 中有两个“根”元素?
问题描述
通常,您必须在模板中放置一个根元素,例如<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>
推荐阅读
- sql-server - SQL Server SSMS 批量插入访问被拒绝
- java - 我如何通过java代码将单个文件上传到指定项目的指定分支,因为没有合适的api接口
- reactjs - 当在 React 中使用 Lazy 时,Webpack 会执行 Tree Shaking 吗?
- go - Glide 或 dep 依赖问题,供应商中的依赖不平坦
- android - ImageView 未显示在 android 中使用相机捕获的图像
- python - 将给定的节点链(链表)分成两半,返回另一半
- reactjs - React firestoreConnect 限制更新频率
- azure - 如果 Azure Function 处理消息失败,是否可以将 Azure Event Hub 配置为保留消息?
- css - 视频标签对象适合替代方案
- java - 区分 Rest API 中的保存和提交