简体   繁体   English

reactjs中如何使用外部js文件

[英]How to use external js files in reactjs

I am trying to convert bootstrap 4 template into reactjs bootstrap is working fine but there are other javascript plugins also and I don't know how to use.我正在尝试将 bootstrap 4 模板转换为 reactjs bootstrap 工作正常,但还有其他 javascript 插件,我不知道如何使用。 Any suggestions would be appreciated.任何建议,将不胜感激。

Update: Please, don't mix jQuery and React.更新:请不要混用 jQuery 和 React。 It could be difficult to handle the DOM and VirtualDOM.处理 DOM 和 VirtualDOM 可能很困难。 Just try it if you really need to:如果您确实需要,请尝试一下:

Try to invoke the scripts and append it when componentDidMount at Root component.尝试调用脚本并在 componentDidMount 位于 Root 组件时附加它。 Here is a snippet:这是一个片段:

//#Write some like this in the App.js for example, since it's the main component:
componentDidMount(){
    //An array of assets
    let scripts = [
        { src: "assets/vendor/jquery/jquery.js" },
        { src: "assets/vendor/bootstrap/js/bootstrap.js" },
        { src: "assets/vendor/jquery-placeholder/jquery.placeholder.js" },
        { src: "assets/javascripts/theme.js" },
        { src: "assets/javascripts/theme.custom.js" },
        { src: "assets/javascripts/theme.init.js" }
    ]
    //Append the script element on each iteration
    scripts.forEach(item => { 
        const script = document.createElement("script")
        script.src = item.src
        script.async = true
        document.body.appendChild(script)
    })    
 }

Include the script tag in your index.html在 index.html 中包含脚本标签

Let's say if you want to include JQuery in your ReactJs app假设你想在你的 ReactJs 应用程序中包含 JQuery

Include following in index.htmlindex.html中包含以下内容

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Use this in following code and it works well在下面的代码中使用它并且效果很好

 import React, { Component } from 'react'; class App extends Component { constructor(){ super() this.callJquery = this.callJquery.bind(this); } callJquery(){ window.$("#sample").click(function(){ alert("Text: Button Clicked"); }); } render() { return ( <div className="App"> <div id="sample" onClick={this.callJquery}> Hellow </div> </div> ); } } export default App;

Similarly, you can use any library by including in index.html and then use it.同样,您可以通过包含在 index.html 中然后使用它来使用任何库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM