我有一个相对简单的问题,试图将内联脚本添加到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实际上在使用,我不想分享。


当前回答

我有原始的html字符串与javascript/Jquery 我安装了NPM库dangerous -set-html-content NPM I危险地设置html内容

import InnerHTML from 'dangerously-set-html-content'
<div>
<InnerHTML html={html}/>
</div>

or

import InnerHTML from 'dangerously-set-html-content'
const renderhtml=`<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title> is not defined</title>$(document).ready(function(){    $("button").click(function(){        alert("jQuery is working perfectly.");    });      });</script></head><body>    <button type="button">Test jQuery Code</button></body></html>`

<div>
<InnerHTML html={renderhtml}/>
</div>

确保你添加了jquery cdn到public/index.html文件

 <script          src="https://code.jquery.com/jquery-3.3.1.min.js"          integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="          crossorigin="anonymous"          async="true"        ></script>

其他回答

除了上面的答案,你还可以这样做:

import React from 'react';

export default class Test extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.innerHTML = "document.write('This is output by document.write()!')";
    this.instance.appendChild(s);
  }

  render() {
    return <div ref={el => (this.instance = el)} />;
  }
}

div被绑定到此,脚本被注入其中。

演示可以在codesandbox.io上找到

老实说,对于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>

这个答案解释了这种行为背后的原因。

任何渲染脚本标签的方法都不能像预期的那样工作:

为外部脚本使用script标记 使用dangerouslySetInnerHTML

Why

React DOM (web上的React渲染器)使用createElement调用将JSX渲染为DOM元素。

createElement使用innerHTML DOM API最终将这些添加到DOM(参见React源代码中的代码)。innerHTML不执行作为安全考虑而添加的脚本标记。这就是为什么React中的渲染脚本标签不能按预期工作的原因。

关于如何在React中使用脚本标签,请查看本页的其他答案。