如何在React / JSX文件中添加脚本标记?

时间:2017-08-17 12:52:40

标签: javascript reactjs typescript

    private get mouseGestureSettingView() {
    const {selectedMenu} = this.state;
    return ( selectedMenu == 2 ?
      <script src="../../assets/js/extensions/mouse-gesture/options.js"></script>
      
    <div className={styles.settingForm}>
        <h3>Mouse Gesture</h3>
                    <div className={options.opts}>
            <div className={options.opttitle} data-i18ninner={'newadd'}></div>
            <div className={options.optcontent}>
                <form>
                    <input id={'addgesture'} className={options.newadd} type={'button'} value={'newgesturess'}/>
                </form>
            </div>
        </div>
        <div className={options.opts}>
            <div className={options.opttitle} data-i18ninner={'editgesture'}></div>
            <div className={options.optcontent} id={'editgesture'}></div>
        </div>
        <div style={{clear:'both'}}></div>
        </div>
      : null
    );
  }

我想对React组件使用内联脚本。我这样想。我的方法应该是什么?我找不到太多信息。我想在应用页面上选择此组件时加载脚本。

3 个答案:

答案 0 :(得分:1)

您需要做的是进行codesplitting。

没有代码拆分

+在第一次启动时加载

import Login from './Login'
import Home from './Home'

const App = ({ user }) => (
  <Body>
    {user.loggedIn ? <Route path="/" component={Home} /> : <Redirect to="/login" />}
    <Route path="/login" component={Login} />
  </Body>
)

使用代码拆分:

import Async from 'react-code-splitting'

import Login from './Login'
const Home = () => <Async load={import('./Home')} />
const LostPassword = props => <Async load={import('./LostPassword')} componentProps={props}/>

const App = ({ user }) => (
  <Body>
    {user.loggedIn ? <Route path="/" component={Home} /> : <Redirect to="/login" />}
    <Route path="/login" component={Login} />
    <Route path="/lostpassword" component={LostPassword} />
  </Body>
)

有几种方法可以做到这一点,例如:https://github.com/didierfranc/react-code-splitting

答案 1 :(得分:0)

在给定js文件的顶部使用importrequire来添加自定义脚本或自定义css,但我同意您应该检查它以确保一切都符合您的预期。

示例:

import "../../assets/js/extensions/mouse-gesture/options.js";

或者,如果您只想在使用方法时导入脚本:

myMethod() {
  require("../../assets/js/extensions/mouse-gesture/options.js");
  ...
}

答案 2 :(得分:0)

您可以尝试以下库:npm install --save react-script-tag

https://www.npmjs.com/package/react-script-tag

import React, { Component } from 'react';
import ScriptTag from 'react-script-tag';

class Demo extends Component {

    render() {
        return (<ScriptTag isHydrating={true} type="text/javascript" src="some_script.js" />);
    }
}