推荐两种引入的方法, 当然也可以自己编写一个 JS 类 (ES6 语法) 实现动态插入 JS 到页面, 然后在 React 项目引入.
第一种: 使用插件 react-load-script
如果没有安装可以使用 yarn add react-load-script 或者 NPM install react-load-script, 看你使用哪个包管理工具.
然后你就可以像使用 React 组件那样插入 JS, 如下代码.
- import React from 'react';
- import Script from 'react-load-script';
- class DynamicScriptExample extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- scriptStatus: 'no'
- }
- }
- handleScriptCreate() {
- this.setState({ scriptLoaded: false })
- }
- handleScriptError() {
- this.setState({ scriptError: true })
- }
- handleScriptLoad() {
- this.setState({ scriptLoaded: true, scriptStatus: 'yes' })
- }
- render() {
- return (
- <>
- <Script
- url="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"
- onCreate={this.handleScriptCreate.bind(this)}
- onError={this.handleScriptError.bind(this)}
- onLoad={this.handleScriptLoad.bind(this)}
- />
- <div > 动态脚本引入状态:{this.state.scriptStatus}</div>
- </>
- );
- }
- }
- export default DynamicScriptExample;
第二种: 直接在 项目 / Public 目录下的 index.html 中引入.
本文来自 React 答疑 https://www.html.cn/qa/react/ 栏目, 欢迎学习!
来源: http://www.css88.com/qa/react/15079.html