如何在同一页面上包含两次相同的React应用程序



我有一个使用CRA v2创建的简单应用程序,它在帖子列表后提供了一个"加载更多"按钮。页面上显示的默认帖子是基于一组标准(即特定的帖子类型、分类术语等(在服务器端生成的,"加载更多"按钮查询API以显示更多符合相同标准的帖子。

我的页面在一个页面上会有未定义(但>1(个帖子列表,并且不是所有列表都在附近,所以整个列表不可能存在于一个应用程序中。我需要能够在每个页面上呈现应用程序不止一次,并让它们独立运行。

在最好的情况下,我可以做这样的事情:

<ul class="posts  posts--foo">[first list of posts from the "foo" post type go here]</ul>
<div id="app-root" data-post-type="foo"></div>

<ul class="posts  posts--bar">[second list of posts from the "bar" post type go here]</ul>
<div id="app-root" data-post-type="bar"></div>

<script src="main.7a3cc682.js"></script> <!-- built script-->

我意识到这不会像写的那样奏效。这可能吗?如果可能,最好的方法是什么?

我能够使用这个问题的答案找到解决方案。以下是它的样子:

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import render from 'react-dom';
import App from './App';    
window.mount = function(id) {
let app = document.getElementById(id);
ReactDOM.render( <WPLoadMore {...(app.dataset)} />, document.getElementById(id) );
}

然后在我的HTML中:

<script src="build/static/js/main.7a3cc682.js"></script>
<ul class="posts  posts--foo"></ul>
<div id="app1" data-post-type="foo"></div>
<script type="text/javascript">mount("app1");</script>
<ul class="posts  posts--bar"></ul>
<div id="app2" data-post-type="bar"></div>
<script type="text/javascript">mount("app2");</script>

唯一有点不确定的是,在我的公共目录中的index.html中,我需要将mount((移到</body>标记的外部,以便它在所有React脚本之后加载,如下所示:

</body>
<script type="text/javascript">mount("wplm");</script> <!-- included outside the body so this works in development -->
</html>

最新更新