我想js在React使用Helmet組件中包含并運行一些檔案。這是簡單的代碼:
index.js:
import React from "react";
import ReactDOM from "react-dom";
import { Helmet } from "react-helmet";
import "./styles.css";
function App() {
console.log("op");
return (
<div className="App">
<Helmet>
<script src="hello.js" type="text/jsx" />
</Helmet>
<h1>Hellok CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
以及js包含和運行的超簡單腳本:
你好.js:
console.log("opl882...")
document.body.style.backgroundColor = "red";
但是腳本似乎不起作用!- 我沒有更改控制臺輸出和/或背景顏色。當我將js代碼用作行內代碼時,這很奇怪:
<Helmet>
<script type="text/javascript">
console.log("opl882..."); document.body.style.backgroundColor = "red"
</script>
</Helmet>
有用!
為什么外部js檔案不起作用?
uj5u.com熱心網友回復:
我通常不使用腳本標簽在 react 中實作 .js 檔案。相反,您應該像這樣在頂部匯入它(假設 './hello.js' 是檔案的路徑):
import './hello.js'
該檔案也必須位于 src 檔案夾內。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/406975.html
標籤:
