我想将脚本文件添加到 jsx 元素。
该脚本文件包含一个简单的console.log('script ran')内容(我想添加一个实际的脚本文件,但出于测试目的,我选择了这个最小的代码)。
// editor.js
console.log('script ran')
Run Code Online (Sandbox Code Playgroud)
// App.jsx
import React, { useEffect } from 'react'
const App = () => {
useEffect(() => {
const script = document.createElement('script')
script.src = '/editor.js'
document.body.appendChild(script)
}, [])
return <></>
}
Run Code Online (Sandbox Code Playgroud)
这会引发以下错误
Uncaught SyntaxError: Unexpected token '<' at editor.js 1:1
Run Code Online (Sandbox Code Playgroud)
文件夹结构:
/
package.json
editor.js
src/
App.js
index.js
Run Code Online (Sandbox Code Playgroud)
我尝试添加type="text/javascript", type="text/babel",async=true但似乎没有任何效果。
editor.js当我在开发者工具中检查该文件时,它显示一个 html 文件(我网站的 404 页面)
使用时type="text/babel"不会抛出任何错误,但也不会执行脚本(console.log 永远不会打印)
我在这里做错了什么?另外,我想要一个不使用 React Helmet 的解决方案
React …