我用
创建了一个基本的反应应用程序npx create-react-app
我可以在index.js
中创建组件,并且我可以将它们渲染到index.html
中的元素。
然而,这是我唯一可以呈现它们的页面,我不能在login.html
页面或index.html
以外的任何其他页面上使用相同的组件
我正在使用npm start
进行测试。
答案 0 :(得分:1)
通常React用于单页面应用程序,因此您只需在单个页面中呈现应用程序,然后使用路由(通常使用react-router
)来模拟浏览器导航。
但是你可以在多个页面上呈现它......你只需要在其他页面上复制你的激活JavaScript
只需在login.html
上复制(取自默认的create-react-app输出):
<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>
答案 1 :(得分:1)
你为什么需要这个?请记住,就其本身而言,React声称自己是SPA(单页应用程序)。这应该足以让您了解单页是(应该)index.html。
无论如何,您可以通过查看create-react-app创建的默认index.html文件以及manifest.json文件来完成此操作。
从manifest.json开始,你应该有这个JSON:
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": "./index.html",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
或类似的东西。您可以选择一个“start_url”属性,这是create-react-app webpack开发服务器的起点,默认情况下,当您在运行它的本地地址请求任何路径时,它将为您提供服务(localhost:3000通常为)。通过更改此属性,您可以将其设置为所需的页面,例如的login.html。
现在,查看index.html默认代码,您应该具有以下内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
</body>
</html>
如您所见,在页面的末尾有一个
<div id="root"></div>
这正是React渲染ReactDOM.render(jsx,ElementID)jsx的地方。事实上,如果你查看index.js,ReactDOM就像:
ReactDOM.render(
<Something />,
, document.getElementByID('root'));
您可以看到ElementID('root')是要渲染jsx()的div元素的id。如果您创建一个新页面,比如login.html,复制粘贴index.html内容并更改元素ID,则可以选择在其中呈现您的内容,同时更改ReactDOM.render()的引用ElementID。 在这方面你应该得到你想要的结果,但如前所述,在我看来你不应该需要这个。