javascript 如何在反应组件中加载脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49851104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to load script in react component
提问by Ashh
I am having following script file
我有以下脚本文件
<script language="javascript">
document.write('<script language="javascript" src="http://tickettransaction.com/?bid='+bid+'&sitenumber='+site+'&tid=event_dropdown" ></' + 'script>');
</script>
I follow this Adding script tag to React/JSXbut it does not work for me...
我按照这个将脚本标签添加到 React/JSX但它对我不起作用......
How do I load the script in my react component?
如何在我的 React 组件中加载脚本?
回答by Ashh
After a lots of R&D finally I found my solution.
经过大量的研发,我终于找到了我的解决方案。
I have used npm postscribeto load script in react component
我曾经npm postscribe在反应组件中加载脚本
postscribe('#mydiv', '<script language="javascript" src="http://tickettransaction.com/?bid='+bid+'&sitenumber='+site+'&tid=event_dropdown"></script>')
回答by Sushil
the following method is worked for me. try, hope it will work for you. basically, you can create a script tag and append it to the body tag. like this--
以下方法对我有用。试试吧,希望对你有用。基本上,您可以创建一个脚本标记并将其附加到正文标记。像这样 -
var tag = document.createElement('script');
tag.async = true;
tag.src = 'THE PATH TO THE JS FILE OR A CDN LINK';
var body = document.getElementsByTagName('body')[0];
body.appendChild(tag);
you can use this on a life cycle hook of react like this.
你可以在像这样反应的生命周期钩子上使用它。
componentDidMount() {
var loadScript = function (src) {
var tag = document.createElement('script');
tag.async = false;
tag.src = src;
var body = document.getElementsByTagName('body')[0];
body.appendChild(tag);
}
loadScript('PATH TO THE JS FILE OR CDN URL');
}
回答by Alex Hughes
I recommend using React Helmet. I've used it on a couple of Create-React-Apps, and it allows you to write actual script tags combined with vanilla JS.
我推荐使用React Helmet。我已经在几个 Create-React-Apps 上使用过它,它允许您结合 vanilla JS 编写实际的脚本标签。
It makes the process a lot smoother. So for you it'd be something like this once you've imported React Helmet.
它使过程更加顺畅。所以对你来说,一旦你导入了 React Helmet,它就会是这样的。
<script language="javascript" src='http://tickettransaction.com/?bid='+ bid + '&sitenumber='+ site +'&tid=event_dropdown' ></ script>
回答by Yash Thakur
You can follow my answer over here: add third-party js library to Create React App
您可以在此处按照我的回答进行操作:将第三方 js 库添加到 Create React App

