Jon*_*nny 0 javascript reactjs trustpilot next.js
我正在尝试将 Trustpilot TrustBox 添加到 Next.js 应用程序。
我的 componentDidMount 中有这个:
var trustbox = document.getElementById('trustbox');
window.Trustpilot.loadFromElement(trustbox);
Run Code Online (Sandbox Code Playgroud)
这在我的脑海中:
<script type="text/javascript" src="//widget.trustpilot.com/bootstrap/v5/tp.widget.bootstrap.min.js" async></script>
Run Code Online (Sandbox Code Playgroud)
这在我的 html 中:
<div id="trustbox" className="trustpilot-widget" data-locale="en-GB" data-template-id="XX" data-businessunit-id="XX" data-style-height="130px" data-style-width="100%" data-theme="light" data-stars="5" data-schema-type="Organization">
<a href="https://uk.trustpilot.com/review/XX" target="_blank">Trustpilot</a>
</div>
Run Code Online (Sandbox Code Playgroud)
这适用于热重载。例如,如果我在服务器运行时添加代码。但是 o 重新加载它会中断,我收到以下错误:
无法读取未定义的属性“loadFromElement”
有任何想法吗?
弄清楚了。您需要在 componentDidMount 中添加以下代码以确保首先加载外部 js。
componentDidMount() {
var aScript = document.createElement('script');
aScript.type = 'text/javascript';
aScript.src = "//widget.trustpilot.com/bootstrap/v5/tp.widget.bootstrap.min.js";
aScript.async = "true"
document.head.appendChild(aScript);
aScript.onload = function () {
var trustbox = document.getElementById('trustbox');
window.Trustpilot.loadFromElement(trustbox);
};
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助任何坚持同样事情的人。
归档时间: |
|
查看次数: |
1365 次 |
最近记录: |