[英]How to properly run a third party script in react?
我需要在 React 應用程序中添加用 bitrix 制作的支持聊天 - 這是一個通常添加到 index.html 文件的腳本。 示例腳本:
<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>
目前,我已經實現了如下連接:用腳本創建了一個組件
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)} />
}
}
並將其連接到應用程序的根目錄
import Script from './Script '
const App = () => {
return(
<>
<App />
<Script />
</>
)
}
它有效,但我認為此解決方案不是最正確的解決方案。 如果有人可以幫助在反應式應用程序(react、vue)中正確運行外部腳本,我將不勝感激。 提前致謝!!
將它放在 index.html 中很好,也是最合規的方法。
不這樣做的唯一原因是:
由於這些似乎都不是這里的情況,我會將它保留在 index.html 中。
我記得有一個叫做dangerousSetInnerHTML 的屬性,你可以在React 官方網站上查找。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.