1 回答

TA貢獻1824條經驗 獲得超6個贊
您可以訪問使用var其他腳本定義的任何變量(在您的腳本之前連接并且未標記為async)。
好吧,如果你在你的 react-app 代碼之前連接你的 js 文件,你可以訪問所有使用var.
例如
索引.html
<html>
...
<body>
<script src="js-file.js" />
<script src="react-code.js" />
</body>
</html>
js-file.js
var mySharedVariable = "Example";
react-code.js 它是 webpack 包(的 js 結果npm run build)
...
export class MyComponent extends Component {
render() {
return mySharedVariable;
}
}
...
MyComponent 將呈現字符串“示例”
如果您使用 typescript,則必須在使用 like 之前聲明 mySharedVariable
declare let mySharedVariable: string;
為什么不能使用async腳本?你可以閱讀這篇文章
UPD
所以,讓我們一步一步地一起做
1) 使用 cra 創建反應應用
npx create-react-app my-app
2)創建文件external.js并將其放在公共文件夾(index.html旁邊)(如果您有遠程文件,請通過此步驟)
var external = "external";
3) 修改你的 index.html 文件(在結束 body 標簽之前添加一行)
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<!-- src is path to your js file -->
<script src="external.js"></script> <!-- add this line -->
</body>
4) 修改你的 App.js 文件
import React from 'react';
import './App.css';
function App() {
return (
<h1>{external}</h1>
);
}
export default App;
5)讓我們啟動你的應用程序
npm run start
添加回答
舉報