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

时间:2018-11-30 18:14:41

标签: reactjs

我有一个使用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-->

我意识到这不会按书面规定进行。这有可能吗?如果可以,那么最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

我能够使用this question的答案找到解决方案。看起来是这样的:

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 中,我需要将{{1的mount()外部 }}标签,以便在所有React脚本之后加载,如下所示:

</body>