简体   繁体   English

如何在反应中正确运行第三方脚本?

[英]How to properly run a third party script in react?

I have a need in a React application to add a support chat made in bitrix - this is a script that is usually added to the index.html file.我需要在 React 应用程序中添加用 bitrix 制作的支持聊天 - 这是一个通常添加到 index.html 文件的脚本。 example script:示例脚本:

   <script>
        (function(w,d,u){
                var s=d.createElement('script');s.async=true;s.src=u+'?'+(Date.now()/60000|0);
                var h=d.getElementsByTagName('script')[0];h.parentNode.insertBefore(s,h);
        })(window,document,'https://someurl.js');
</script>

At the moment, I have implemented the connection as follows: created a component with a script目前,我已经实现了如下连接:用脚本创建了一个组件

import React, { Component } from 'react'

export default class Script extends Component {
  componentDidMount() {
    const s = document.createElement('script')
    // s.type = 'text/javascript'
    s.async = true
    s.innerHTML = "document.write('This is output by document.write()!')"
    s.src =
      'https://someurl.js' +
      '?' +
      ((Date.now() / 60000) | 0)
    this.instance.appendChild(s)
    const h = document.getElementsByTagName('script')[0]
    h.parentNode.insertBefore(s, h)
  }

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

and connected it at the root of the application并将其连接到应用程序的根目录

import Script from './Script '
    const App = () => {
       return(
          <>
            <App />
            <Script />
          </>
       )
    }

It works, but I think this solution is not the most correct one.它有效,但我认为此解决方案不是最正确的解决方案。 If Someone can help to run external script correctly in reactive applications (react, vue) I would be very grateful.如果有人可以帮助在反应式应用程序(react、vue)中正确运行外部脚本,我将不胜感激。 thanks in advance!!提前致谢!!

Putting it in index.html is fine and the most compliant approach.将它放在 index.html 中很好,也是最合规的方法。

The only reasons to not do that would be:这样做的唯一原因是:

  1. Embedding the script is conditional - it depends on something you only know as soon as the React/Vue/etc.嵌入脚本是有条件的——这取决于你只知道 React/Vue/etc. app is running.应用程序正在运行。 Or you want to delay the embedding.或者您想延迟嵌入。
  2. You're hooking something like a Promise into the loading of the script, for example checking when the Bitrix chat is up and running您正在将 Promise 之类的东西挂钩到脚本的加载中,例如检查 Bitrix 聊天何时启动并运行
  3. You need to pass values only known to the React/Vue/etc.你需要传递只有 React/Vue/etc 知道的值。 app to the embedding of the script (api key for example) app 嵌入脚本(例如 api 密钥)

Since none of these seem to be the case here, I'd keep it in index.html.由于这些似乎都不是这里的情况,我会将它保留在 index.html 中。

我记得有一个叫做dangerousSetInnerHTML 的属性,你可以在React 官方网站上查找。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM