【发布时间】:2022-09-22 21:10:22
【问题描述】:
我有一个 Javascript 模块,如下所示:
export function test() {
return \"Hello\";
}
我需要在 React 中导入这个脚本。
这是我尝试过的:
- 定义了一个 useScript 方法:
const useScript = ({ onLoad } : { onLoad: any }) => { useEffect(() => { const script = document.createElement(\'script\'); script.type = \"module\"; script.src = \"path/to/test.js\"; script.onload = onLoad document.body.appendChild(script); return () => { document.body.removeChild(script); } }, [onLoad]); };- 使用它在 React 组件中加载脚本:
const getTest = () => { window[\"test\"](); } useScript({ onLoad: getTest });这给了我错误:
window.test is not a function请注意,如果我从 JS 文件中删除
export则它可以工作。但是,我需要export并且不确定为什么添加导出会破坏它。 有什么线索吗?
标签: javascript reactjs webpack module es6-modules