将第三方js库添加到Create React App [英] add third-party js library to Create React App

查看:311
本文介绍了将第三方js库添加到Create React App的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Create React App中使用chartIQ库。我只是通过在我的index.html文件< script src = chartiq / js / chartiq.js>< / script> 中使用脚本标记来添加它的这样工作,但感觉不对。因为我只需要一个组件的库,最好以某种方式将库仅导入到该组件。有什么办法可以正确地做到这一点吗?

I am using chartIQ library in my Create React App. I added it just by using script tag in my index.html file <script src="chartiq/js/chartiq.js"></script> and it works that way, but it does not feel right. Because I need this library only for one component and it would be better to import somehow this library only to this component. Is there any way to do this correcly?

推荐答案

您可以通过以下方式使用它:

You can use it in the following way:

function loadScript(url, callback){

    let script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

,然后在 componentDidMount()<上使用此函数/ code>加载外部脚本。

and then use this function on componentDidMount() to load the external script.

这篇关于将第三方js库添加到Create React App的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆