React JS中是否可将多个JS文件的元素渲染到root根节点?
React 多文件内容渲染到同一root节点解答
可以将多个JS文件中的元素渲染到同一个root根节点,但不能通过多次调用ReactDOM.render的方式实现,你当前代码不生效的原因有三个:
- 你的React项目默认以index.js为打包入口,你没有在index.js中引入one.js文件,one.js的代码压根不会执行,自然不会输出对应内容
- 就算你引入了one.js,对同一个root节点多次调用渲染方法,后执行的渲染会直接覆盖root内已有的全部内容,不会做内容叠加
- 你one.js中定义的
const b="abc {a}"是普通字符串,不是JSX结构,就算直接渲染也不会解析{a}的变量插值,无法得到你想要的效果
正确实现方式
不要在多个JS文件中单独调用渲染方法渲染同一个root,而是将各文件需要渲染的内容封装为组件导出,在入口文件中导入所有需要的组件,组合成完整的渲染树后一次性渲染到root节点即可。
修改后的one.js代码
import React from 'react'; const a = "def"; // 封装为组件导出,用JSX格式写结构才能正确解析变量插值 const OneComponent = () => <div>abc {a}</div>; export default OneComponent;
修改后的index.js代码
React 18 版本写法
import React from 'react'; import ReactDOM from 'react-dom/client'; import 'bootstrap/dist/css/bootstrap.css'; import Counter from './components/counter'; // 导入one.js导出的组件 import OneComponent from './one'; const x = "one"; // 组合所有要渲染的内容 const App = ( <div> <h2>Zero, {x}</h2> <h1>{x == "one" ? "two" : "three"}</h1> {/* 插入one.js的内容 */} <OneComponent /> </div> ); const root = ReactDOM.createRoot(document.getElementById('root')); root.render(App);
React 17 及更早版本写法
import React from 'react'; import ReactDOM from 'react-dom'; import 'bootstrap/dist/css/bootstrap.css'; import Counter from './components/counter'; import OneComponent from './one'; const x = "one"; const App = ( <div> <h2>Zero, {x}</h2> <h1>{x == "one" ? "two" : "three"}</h1> <OneComponent /> </div> ); ReactDOM.render(App, document.getElementById('root'));
修改后即可在页面上同时看到两个文件的输出内容。
内容的提问来源于stack exchange,提问作者ItsRibhav
相关产品推荐
相关产品推荐

