我正在尝试与codesandbox.io作出反应。启动新项目时,将显示默认代码。
在index.js文件中,我们引用了HTML中的"root“元素。但是我没有意识到JS文件是如何连接到HTML文件的。
在Vanilla中,HTML文件可以有一个"script“标记。为什么这里没有必要使用“脚本”标记?
代码
index.js
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
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>
create a production bundle, use `npm run build` or `yarn build`.
</body>
发布于 2019-03-05 02:38:28
如果您将弹出应用程序并检查webpack.config文件,您可能会发现以下部分:
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin(...)
]因此,只需webpack将包脚本注入HTML页面。如果你没有创建-反应-应用程序,你将不得不使用脚本标签或自己编写类似的插件。
另外,您正在查看源代码。如果您将服务于应用程序并检查检查器,您将在脚本标记中看到捆绑包。
发布于 2019-03-05 04:37:33
如何将JS文件连接到HTML?
这是一个如何反应的例子。
index.html:
<div id="root"></div>index.js:
ReactDOM.render(<App/>, document.getElementById('root'))app.js:
function App() {
return (
<div className="App">
Hello React!
</div>
);
}这是JSX,它将被转换为其他的东西并创建一个DOM in React,类似于:
const app = document.createElement('div');
app.innerText= 'Hello React!';所以,现在您有了一个在app.js中创建的dom(app),在index.js中有一个dom(根)查询,ReactDOM.render(,rootDOM)只执行如下操作:
rootDom.appendChild(app);最后,您的组件(App)将显示在根域;
为什么这里没有必要使用“脚本”标记?
因为webpack是为你做的,webpack会将你的代码捆绑到一个javascript文件中,并插入到index.html的链接。
https://stackoverflow.com/questions/54994543
复制相似问题