我想包含jquery.min.js并添加一个外部javascript文件,并在现有的react js文件中调用javascript函数。
我在下面做了,但是没用
const VoCaaSComponentbtn = (
<React.Fragment>
<div>
<script type="text/javascript"src="https:xxxx/jquery-3.3.1.min.js"></script>
<script type="text/javascript"src="https:xxx/microsurvey" defer="defer"></script>
<div id="microsurvey" module="true" tab-info="tabname"></div>
<script type="text/javascript"> voc_getsurvey(); </script>
</div>
</React.Fragment>
);
答案 0 :(得分:2)
您可以在公共目录内的indeex.html页面中添加外部JS库。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Web site created using create-react-app" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<script type="text/javascript"src="https:xxxx/jquery-3.3.1.min.js"></script>
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
答案 1 :(得分:2)
您可以将所有脚本导入到主HTML文件中。
如果要在react组件中导入脚本,可以使用以下选项。
选项1:使用纯Javascript和React自定义钩子
创建自定义钩子[ useScript.js ]
import { useEffect } from 'react';
const useScript = url => {
useEffect(() => {
const script = document.createElement('script');
script.src = url;
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, [url]);
};
export default useScript;
使用
import useScript from 'hooks/useScript';
const MyComponent = props => {
useScript('https://use.typekit.net/foobar.js');
// rest of your component
}
选项2:在ComponentDidMount中使用纯Javascript
componentDidMount () {
const script = document.createElement("script");
script.src = url;
script.async = true;
document.body.appendChild(script);
}
选项3: 危险地使用SetInnerHTML
const codeStr = `
<div>
<script type="text/javascript"src="https:xxxx/jquery-3.3.1.min.js"></script>
<script type="text/javascript"src="https:xxx/microsurvey" defer="defer"></script>
<div id="microsurvey" module="true" tab-info="tabname"></div>
<script type="text/javascript"> voc_getsurvey(); </script>
</div>
`
<div dangerouslySetInnerHTML={{ __html: codeStr }} />
答案 2 :(得分:0)
另一种添加外部JavaScript文件的方式。如果您只想添加特定页面或组件。
componentDidMount() {
var script = document.createElement('script')
script.src = // path of external javascript file.
script.class = "external-script"
document.body.appendChild(script);
}