javascript 如何在nextjs中为不同的状态加载不同的脚本?

jm81lzqq  于 2023-02-28  发布在  Java
关注(0)|答案(1)|浏览(129)

目前我想在状态中加载英语和希伯来语的不同脚本。但是即使redux useSelector值更改为希伯来语,希伯来语脚本也不会呈现。它总是在右侧显示英语按钮。现在我的代码如下所示

function HeadCustom({ title }) {
  const { lang } = useSelector((state) => state.language.language);
  const isEng = () => {
    return lang === "eng";
  };
  return (
    <>
      {isEng() ? (
          <Script>
            {`window.interdeal = { "sitekey": "216e47f62cb419bc8207601b49e6dbc6", "Position": "Right", "Menulang": "EN", "domains": { "js": "https://cdn.equalweb.com/", "acc": "https://access.equalweb.com/" }, "btnStyle": { "vPosition": ["80%", null], "scale": ["0.6", "0.6"], "color": { "main": "#5663eb" }, "icon": { "type": 11, "shape": "semicircle", "outline": false } } }; (function (doc, head, body) { var coreCall = doc.createElement('script'); coreCall.src = 'https://cdn.equalweb.com/core/4.4.0/accessibility.js'; coreCall.defer = true; coreCall.integrity = 'sha512-3lGJBcuai1J0rGJHJj4e4lYOzm7K08oEHsg1Llt7x24OOsa/Ca0wwbSi9HhWUn92FKN3fylaq9xmIKVZnUsT3Q=='; coreCall.crossOrigin = 'anonymous'; coreCall.setAttribute('data-cfasync', true); body ? body.appendChild(coreCall) : head.appendChild(coreCall); })(document, document.head, document.body);`}
          </Script>
      ) : (
          <Script>
            {`window.interdeal = { "sitekey": "b1deb4b25a71a4e1d747032724407d56", "Position": "Right", "Menulang": "HEB", "domains": { "js": "https://cdn.equalweb.com/", "acc": "https://access.equalweb.com/" }, "btnStyle": { "vPosition": ["80%", null], "scale": ["0.8", "0.8"], "color": { "main": "#5663eb" }, "icon": { "type": 11, "shape": "semicircle", "outline": false } } }; (function (doc, head, body) { var coreCall = doc.createElement('script'); coreCall.src = 'https://cdn.equalweb.com/core/4.4.1/accessibility.js'; coreCall.defer = true; coreCall.integrity = 'sha512-tq2wb4PBHqpUqBTfTG32Sl7oexERId9xGHX2O3yF91IYLII2OwM1gJVBXGbEPaLmfSQrIE+uAOzNOuEUZHHM+g=='; coreCall.crossOrigin = 'anonymous'; coreCall.setAttribute('data-cfasync', true); body ? body.appendChild(coreCall) : head.appendChild(coreCall); })(document, document.head, document.body);`}
          </Script>
      )}
    </>
  );
}

您可以在Menulang属性中查看脚本语言

ruoxqz4g

ruoxqz4g1#

不能动态更改<script>元素。
根据你的实际需要,我建议

详细信息:

您可以 * 添加 * <script>元素,但永远不能删除它,或者更准确地说:您可以删除元素,但永远不能使脚本“尚未执行”。
使用React/Next.js的一般方法更像这样:

useEffect( () => {
    window.interdeal = {
        Menulang: lang,
        sitekey: ...
        ...
    }   
}, [ lang ] );

此外,在使用React时,您不应该手动操作DOM(例如,使用body.appendChild时)。如果您无论如何都需要这样做,则必须在useEffect中进行。

相关问题