如何在 index.html 以外的任何其他页面上呈现 React 组件 [英] How to render a react component on any other page other than index.html
问题描述
我用
npx create-react-app
我可以在 index.js
中创建组件,并且我可以将它们渲染到 index.html
中的元素.
I can create components in the index.js
and I'm able to render them to an element in the index.html
.
然而,这是我也可以呈现它们的唯一页面,例如,我不能在 login.html
页面或除 index.html<之外的任何其他页面上使用相同的组件/代码>
However that's the only page I can render them too, I can't for example use the same component on the login.html
page or any other page other than index.html
我正在用 npm start
测试这个.
I'm testing this with npm start
.
推荐答案
React 通常用于单页面应用,所以你只需在单页面渲染应用,然后使用路由(使用 react-router
通常)用于模拟浏览器导航.
Commonly React is used for single page applications, so you just render the app in a single page, then use routing (with react-router
commonly) for simulate browser navigation.
但是您可以在多个页面上呈现它...您只需要在其他页面上复制您的激活 JavaScript
However you can render it on multiple pages... you only need to copy your activation JavaScript on other pages
只需将其复制到您的 login.html
(取自默认的 create-react-app 输出):
Just copy this on your login.html
(taken from default create-react-app output):
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<script type="text/javascript" src="/static/js/bundle.js"></script>
这篇关于如何在 index.html 以外的任何其他页面上呈现 React 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!