Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

javascript - 将脚本标签添加到React / JSX(Adding script tag to React/JSX)

I have a relatively straightforward issue of trying to add inline scripting to a React component.

(我有一个相对直接的问题,试图将内联脚本添加到React组件。)

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>
        );
    }
};

I have also tried:

(我也尝试过:)

<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: Ignore the foobar, I have a real id actually in use that I didn't feel like sharing.

(PS:忽略foobar,我确实有一个真正的ID正在使用,而我不想共享。)

  ask by ArrayKnight translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

(您是否想在每次渲染此组件时一次或一次将该组件安装到DOM中时一次又一次地获取并执行脚本?)

Perhaps try something like this:

(也许尝试这样的事情:)

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

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

    document.body.appendChild(script);
}

However, this is only really helpful if the script you want to load isn't available as a module/package.

(但是,这仅在要加载的脚本不能作为模块/软件包提供时才真正有用。)

First, I would always:

(首先,我将始终:)

  • Look for the package on npm

    (在npm上寻找包裹)

  • Download and install the package in my project ( npm install typekit )

    (在我的项目中下载并安装该软件包( npm install typekit ))

  • import the package where I need it ( import Typekit from 'typekit'; )

    (import我需要的包( import Typekit from 'typekit'; ))

This is likely how you installed the packages react and react-document-title from your example, and there is a Typekit package available on npm .

(这可能是您从示例中安装软件包reactreact-document-title的方式,并且npm上有一个Typekit软件包 。)

Update:

(更新:)

Now that we have hooks, a better approach might be to use useEffect like so:

(现在我们有了钩子,更好的方法可能是像这样使用useEffect :)

useEffect(() => {
  const script = document.createElement('script');

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

  document.body.appendChild(script);

  return () => {
    document.body.removeChild(script);
  }
}, []);

Which makes it a great candidate for a custom hook (eg: hooks/useScript.js ):

(这使其成为自定义钩子的理想选择(例如: hooks/useScript.js ):)

import { useEffect } from 'react';

const useScript = url => {
  useEffect(() => {
    const script = document.createElement('script');

    script.src = url;
    script.async = true;

    document.body.appendChild(script);

    return () => {
      document.body.removeChild(script);
    }
  }, [url]);
};

export default useScript;

Which can be used like so:

(可以这样使用:)

import useScript from 'hooks/useScript';

const MyComponent = props => {
  useScript('https://use.typekit.net/foobar.js');

  // rest of your component
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...