将脚本标签添加到React / JSX [英] Adding script tag to React/JSX

查看:207
本文介绍了将脚本标签添加到React / JSX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个比较简单的问题,试图添加内联脚本到一个React组件。我到目前为止:

I have a relatively straightforward issue of trying to add inline scripting to a React component. What I have so far:

'use strict';

import '../../styles/pages/people.scss';

import React, { Component } from 'react';
import DocumentTitle from 'react-document-title';

import { prefix } from '../../core/util';

export default class extends Component {
    render() {
        return (
            <DocumentTitle title="People">
                <article className={[prefix('people'), prefix('people', 'index')].join(' ')}>
                    <h1 className="tk-brandon-grotesque">People</h1>

                    <script src="https://use.typekit.net/foobar.js"></script>
                    <script dangerouslySetInnerHTML={{__html: 'try{Typekit.load({ async: true });}catch(e){}'}}></script>
                </article>
            </DocumentTitle>
        );
    }
};

我也尝试过:

<script src="https://use.typekit.net/foobar.js"></script>
<script>try{Typekit.load({ async: true });}catch(e){}</script>

这两种方法似乎都不会执行所需的脚本。我猜这是一件简单的事,我失踪了。可以有人帮忙吗?

Neither approach seems to execute the desired script. I'm guessing it's a simple thing I'm missing. Can anybody help out?

PS:忽略foobar,我有一个真正的id,实际上我不喜欢分享。

PS: Ignore the foobar, I have a real id actually in use that I didn't feel like sharing.

推荐答案

您是否希望在将此组件装载到DOM中时获取并执行脚本一次,还是要每次该组件抓取并执行该组件被渲染?

Do you want to fetch and execute the script once when this component is mounted into the DOM, or do you want to fetch and execute it every time this component is rendered?

也许尝试这样的一个例子:

Perhaps try something like this:

    componentWillMount() {
        const script = document.createElement("script");

        script.src = "https://use.typekit.net/foobar.js";
        script.async = true;

        document.body.appendChild(script);
    },

但我强烈建议您重新考虑为什么你是这样做的..有一个在NPM上的Typekit包,你可以 import / require ..

but I highly recommend you re-think why you are doing it this way.. there is a Typekit package on NPM you could just import/require..

这篇关于将脚本标签添加到React / JSX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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