Next.js 中的 Trustpilot TrustBoxes

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”

有任何想法吗?

Jon*_*nny 6

弄清楚了。您需要在 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)

希望这可以帮助任何坚持同样事情的人。


小智 5

对于未来的读者,Trustpilot 现在提供了单页应用程序的文档,您可以在此处找到

我想知道为什么即使有他们的官方文档也没有渲染任何内容,但经过 2 个小时的痛苦,我发现(在我写这篇文章时)你无法在 Brave 导航器上加载他们的小部件......