1 回答
TA贡献1824条经验 获得超6个赞
通过使用自定义 React Hooks 解决了这个问题。相同的逻辑也适用于 next.js
自定义反应挂钩:
import { useEffect } from "react";
// The page will pass in the third party libraries it needs to use
export default function useThirdPartyLib(pagescripts) {
useEffect(() => {
function prepareScripts(...scripts) {
return scripts.reduce((accu, script, index) => {
const scriptTag = document.createElement("script");
scriptTag.src = `/js/${script}`;
scriptTag.id = `${script.split(".")[0].trim()}_${index.toString()}`;
scriptTag.async = false;
accu.push(scriptTag);
return accu;
}, []);
}
// Mount all prepared scripts onto the body
prepareScripts(...pagescripts).map((script) => {
return document.body.appendChild(script);
});
// Do Clean ups
return () => {
prepareScripts(...pagescripts).map((script) => {
const body = document.getElementsByTagName("BODY")[0];
const targetTag = body.querySelector(`#${script.getAttribute("id")}`);
return targetTag.parentNode.removeChild(targetTag);
});
};
}, []);
}
使用 fancyBox 的组件内部的用法
import useThirdPartyLib from "../../../hooks/third-party-libs";
export default function SplashScreen() {
useThirdPartyLib(["jquery.js", "plugins.js", "modal.js"]);
return (
<div style={{ display: "none" }} id="splash_screen">
<a href="/covid-19-test" className="campaign-wrapper">
<img
src="/images/campaigns/campaign-1.png"
width="731"
height="731"
alt="Campaign Pic"
/>
</a>
</div>
);
}
包含 jQuery fancybox 标记的 modal.js 文件
jQuery(function () {
if ($("#splash_screen").length) {
$.fancybox.open({
src: "#splash_screen",
type: "inline",
btnTpl: {
smallBtn:
'<button type="button" data-fancybox-close class="fancybox-button fancybox-close-small my-close" title="{{CLOSE}}"><span class="close-text">Close this Window</span>' +
'<span class="icon"><svg xmlns="http://www.w3.org/2000/svg" version="1" viewBox="0 0 28 28"><path d="M14 16l12-12-1-1-12 12-12-12-1 1 12 12-12 12 1 1 12-12 12 12 1-1z"/></svg></span>' +
"</button>"
}
});
} // EndIf
}); // Docx ready
添加回答
举报