在reactjs中加载脚本标签

时间:2018-12-22 15:01:49

标签: javascript reactjs

我想在项目中加载外部脚本。 我创建了一个用于创建脚本的withScripts.js。

withScripts.js:

import React, { Component } from 'react';

export const loadScripts = scripts => {
  scripts.forEach(s => {
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}${s}`;
    script.async = false;
    document.body.appendChild(script);
  });
};

export const scripts = [
    'scripts/chosen.min.js',
    'scripts/custom.js',
    'scripts/dropzone.js',
    'scripts/infobox.min.js',
    'scripts/jquery.jpanelmenu.js',
    'scripts/magnific-popup.min.js',
    'scripts/jquery-2.2.0.min.js',
    'scripts/maps.js',
    'scripts/markerclusterer.js',
    'scripts/masonry.min.js',
    'scripts/owl.carousel.min.js',
    'scripts/rangeSlider.js',
    'scripts/slick.min.js',
    'scripts/sticky-kit.min.js',
    'scripts/switcher.js',
    'scripts/tooltips.min.js'
];


export default WrappedComponent => {
  return class extends Component {
    componentDidMount() {
      loadScripts(scripts);
    }
    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
};

并在App.js中使用withScrpt.js:

App.js:

import React, { Component } from 'react';
import {BrowserRouter as Router,Switch,Route} from 'react-router-dom';
import HomePage from './screen/HomePage';
import Header from './component/Header';
import Footer from './component/Footer';
import withScripts from './utils/withScripts';

class App extends Component {
    render() {
        return (
            <Router>
                <div id="wrapper">
                    <Header/>
                    <Switch>
                        <Route path="/" exact component={withScripts(HomePage)}/>
                    </Switch>
                    <Footer/>
                </div>
            </Router>
        );
    }
}

export default App;

但是脚本在我的项目中不起作用! 并在控制台选项卡中显示此消息:

SyntaxError:期望的表达式,得到'<'[了解更多] mmenu.min.js:1

SyntaxError:期望的表达式,得到了'<'[了解更多] jquery.counterup.min.js:1

TypeError:$ .jPanelMenu不是函数[了解更多]

当我单击mmenu.min.js:1时显示index.html文件!

0 个答案:

没有答案