我正在尝试将脚本标记插入到react组件中,以加载cookieBot库。
这是我的部件。
class CookieDeclarationSection extends React.Component {
constructor() {
super()
this.state = {
title: "Cookie declaration",
}
}
componentDidMount() {
const script = document.createElement("script")
console.log(script)
script.id = "CookieDeclaration"
script.src = "https://consent.cookiebot.com/XXXX-XXXX-XXXX-XXXXXX"
script.type = "text/javascript"
script.async = true
this.instance.appendChild(script)
}
render() {
return (
<div className="citation__result">
<WideScreenOnlyHeading title={this.state.title} />
<div style={{margin: "16px"}}>
{/*!-- insert SCRIPT TAG here */}
</div>
</div>
)
}
}不管怎么说,我总是
无法读取未定义的属性appendChild
。我在这里错过了什么?谢谢!
发布于 2019-12-04 07:05:15
您应该考虑使用反应安全包来仅使用jsx追加脚本:
import React from "react";
import Safe from "react-safe"
const CookieDeclarationSection = () => (
<div className="citation__result">
<WideScreenOnlyHeading title="Cookie declaration" />
<div style={{margin: "16px"}}>
<Safe.script type="text/javascript" src="https://consent.cookiebot.com/XXXX-XXXX-XXXX-XXXXXX" async></Safe.script>
</div>
</div>
)https://stackoverflow.com/questions/59142421
复制相似问题