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

'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>

这两种方法似乎都不能执行所需的脚本。我猜我错过了一件简单的事。有人能帮忙吗?

PS:忽略foobar,我有一个真正的id实际上在使用,我不想分享。


当前回答

老实说,对于React来说,不要在头文件中添加<script>标签。这是一个痛苦的屁股得到一个回调时,他们已经完全加载。相反,使用像@charlietango/useScript这样的包在需要时加载脚本,并在脚本完成时获得状态更新。

使用示例:

import React from 'react'
import useScript, { ScriptStatus } from '@charlietango/use-script'
 
const Component = () => {
  const [ready, status] = useScript('https://api.google.com/api.js')
 
  if (status === ScriptStatus.ERROR) {
    return <div>Failed to load Google API</div>
  }
 
  return <div>Google API Ready: {ready}</div>
}
 
export default Component

PS.如果你使用redux来告诉其他组件你的脚本何时加载,并且像我一样使用redux-persist,不要忘记在你的redux-persist设置中包含一个修饰符,它总是在redux备份中将脚本加载的redux值设置为false。

其他回答

我最近遇到了一个问题, 尝试了这里给出的多种解决方案,最终满足于iframe, 如果你想在特定的屏幕上集成一个js插件,Iframe似乎可以无缝地工作

<iframe id="xxx" title="xxx" width="xxx" height="xxx" frameBorder="value" allowTransparency srcDoc={` <!doctype html> <html> <head> <title>Chat bot</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> </head> <body style="width:100%"> <script type="text/javascript"> ...... </script> </body> </html> `} />

你可以试着使用下面的语句:

确保你相信剧本

 <script>{`
            function myFunction(index, row) {
                return index;
            }
        `}
</script>

要在head tag <head>中添加脚本标签或代码,请使用react-helmet包。它很轻,有很好的文档。

在script标签中添加Js代码

    function htmlDecode(html) {
      return html.replace(/&([a-z]+);/ig, (match, entity) => {
        const entities = { amp: '&', apos: '\'', gt: '>', lt: '<', nbsp: '\xa0', quot: '"' };
        entity = entity.toLowerCase();
        if (entities.hasOwnProperty(entity)) {
          return entities[entity];
        }
        return match;
      });
    }
  render() {
    const scriptCode = `<script type="text/javascript">
          {(function() {
          window.hello={
            FIRST_NAME: 'firstName',
            LAST_NAME: 'lastName',
          };
          })()}
          </script>`
    return(
      <div dangerouslySetInnerHTML={{ __html: this.htmlDecode(scriptCode) }} />;
    );
  }

这段代码可以通过console.log(windows.hello)进行测试。

老实说,对于React来说,不要在头文件中添加<script>标签。这是一个痛苦的屁股得到一个回调时,他们已经完全加载。相反,使用像@charlietango/useScript这样的包在需要时加载脚本,并在脚本完成时获得状态更新。

使用示例:

import React from 'react'
import useScript, { ScriptStatus } from '@charlietango/use-script'
 
const Component = () => {
  const [ready, status] = useScript('https://api.google.com/api.js')
 
  if (status === ScriptStatus.ERROR) {
    return <div>Failed to load Google API</div>
  }
 
  return <div>Google API Ready: {ready}</div>
}
 
export default Component

PS.如果你使用redux来告诉其他组件你的脚本何时加载,并且像我一样使用redux-persist,不要忘记在你的redux-persist设置中包含一个修饰符,它总是在redux备份中将脚本加载的redux值设置为false。

componentDidMount() {
  const head = document.querySelector("head");
  const script = document.createElement("script");
  script.setAttribute(
    "src",
    "https://assets.calendly.com/assets/external/widget.js"
  );
  head.appendChild(script);
}