如何在jsx中调用script标签?

我想在jsx中按需引入第三方的js,如


// ...
return (
  <div>
    ...
    <script src="http://..."></script>
  </div>
)

虽然在最终的dom中能生成<script src="http://..."></script>

但浏览器并没有真的请求这个远程的js

请问应该怎么做?

阅读 22k
5 个回答
  componentDidMount() {
    setInterval(this.fetchDataSource, 5000);
    const body = document.getElementsByTagName('body')[0];
    const script = document.createElement('script');
    script.src = 'https://cdn.bootcss.com/jquery/3.2.1/core.js';
    body.appendChild(script);
  }

可以这样写,但是这样会有个问题会导致script标签多次加载.

clipboard.png

componentDidMount(){
    var s = document.querySelector("#jsonp");
    s&&s.parentNode.removeChild(s);
    var script = document.createElement("script");
    script.id = "jsonp";
    script.src = 'https://cdn.bootcss.com/jquery/3.2.1/core.js';
    document.body.appendChild(script);
 }

这样只加载一次

好奇怪的写法。
建议写到html中去吧。不要在component中写一些非react组件。

class myComponent extends Component {
    componentDidMount() {
        let s = document.createElement(“script”);
        s.src = “//foursixty.com/media/scripts/fs.slider.v2.5.js”;
        s.setAttribute(“data-feed-id”, “ryee_13”);
        s.async = true;
        this.fourSixtyElement.appendChild(s);
         }

    render() {
        return (
            <div ref={el => (this.fourSixtyElement = el)}></div>
                );
            }
    }

不知道题主解决该问题没有,本人写自用程序时,用到了tradingView的插件,遇到了这个问题,现在提供本人的解决思路:

  1. 将需要引用的第三方script写在index.html中
    image.png
  2. 在需要使用该脚本的组件中提供一个容器标签
    image.png
  3. 在组件钩子函数中动态appendChild
    image.png
  4. 页面效果
    image.png

供参考。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏