我正在尝试使用codesandbox.io进行React。启动新项目时,将显示默认代码。
在index.js文件中,我们引用了HTML文件中的“root”元素。但我没有意识到JS文件是如何连接到HTML文件的。
在Vanilla JS中,HTML文件可以有一个“脚本”标记。为什么这里不需要“脚本”标签?
码
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>
如果您要弹出应用程序并检查webpack.config文件,您可能会发现此部分:
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin(...)
]
因此,只需webpack将包脚本注入HTML页面。如果您在没有create-react-app的情况下使用react,您将不得不使用脚本标记或自己编写类似的插件。
此外,您正在查看源代码。如果您将提供应用程序并检查检查器,您将在脚本标记中看到该包。
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,它将转换为其他内容并在React中创建一个DOM,如:
const app = document.createElement('div');
app.innerText= 'Hello React!';
所以,现在你有一个在app.js中创建的dom(app),你在index.js中有一个dom(root)查询,ReactDOM.render(,rootDOM)就是这样做的:
rootDom.appendChild(app);
最后,你的组件(App)将以root dom显示;
为什么这里不需要“脚本”标签?
因为webpack为你做,webpack会将你的代码捆绑到一个javascript文件中并插入到index.html的链接。