[英]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:不这样做的唯一原因是:
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.