![](/img/trans.png)
[英]Rendering multiple DOM elements from different HTML pages in the same app.js
[英]React render multiple DOM elements from different HTML pages from same index.js
我实质上是在尝试编写一个JavaScript插件,该插件可以嵌入在以react编写的网站上。 我的问题是我需要能够在不使用路由的情况下在不同页面上的DOM元素中呈现组件。 到目前为止,这是我的代码。
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Products from './Products';
const app = (
<ApolloProvider client={client}>
<App />
</ApolloProvider>
)
const products = (
<ApolloProvider client={client}>
<Products />
</ApolloProvider>
)
ReactDOM.render(app, document.getElementById('root'));
ReactDOM.render(products, document.getElementById('products'));
然后,将此代码打包并放在html页面上时。
Index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a href="products.html">Products</a>
<div id="root"></div>
<script src="main.f043f60e.js"></script>
</body>
</html>
Products.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a href="index.html">Home</a>
<div id="products"></div>
<script src="main.f043f60e.js"></script>
</body>
</html>
我的组件的内容未显示。 仅当我在每个页面上都具有DOM元素( product和root )时,该方法才有效,但这违背了目的。 如何在页面上没有所有根元素的情况下完成此任务?
在实现React时,这不是您想要的理想设置。 但是您可以在脚本中执行条件渲染逻辑:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Products from './Products';
const app = (
<ApolloProvider client={client}>
{window.location.href === "https://www.example.com/app.html " ? <App /> : ''}
{window.location.href === "https://www.example.com/products.html " ? <Products/> : ''}
</ApolloProvider>
)
ReactDOM.render(app, document.getElementById('root'));
然后将两个html(在app.html和products.html中)的<body>
都更改为:
<body>
<a href="products.html">Products</a>
<div id="root"></div>
<script src="main.f043f60e.js"></script>
</body>
附言 不建议在使用React时使用该方法。
除非您将应用程序和产品都包含为DOM元素,否则您的.render
不能正常工作的原因大概是由于错误。 即ReactDOM.render(app, document.getElementById('root'));
找不到ID为root的元素。
如果继续建议的结构,这应该可以工作:
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import Products from './Products'; const app = ( <ApolloProvider client={client}> <App /> </ApolloProvider> ) const products = ( <ApolloProvider client={client}> <Products /> </ApolloProvider> ) const rootElement = document.getElementById('root'); if (rootElement) { ReactDOM.render(app, rootElement); } const productsElement = document.getElementById('products'); if (productsElement) { ReactDOM.render(products, productsElement); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.