我希望使用Helmet
组件在React
中包含并运行一些js
文件。这里是一个简单的代码:
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" />
);
}
一个超级简单的 js
脚本来包含和运行:
hello.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
文件不能工作?
type
属性从text/jsx
改为text/javascript
。 - Emiel Zuurbiertext/javascript
时,我收到了一个错误:“意外的令牌'<'”... - Daar44text/javascript
保留不变,并将源更改为 src={"./hello.js"}。 - Bilal Abraham