我知道我有一个类似于here的问题,尽管在我看来这就是我已经在做的事情。
我有一个功能,广告脚本到页面如下所示。
export const appendScript = function (scriptToAppend, sourceScript = true) {
if (sourceScript) {
const script = document.createElement("script");
script.type = "text/javascript";
script.async = false;
script.src = scriptToAppend;
document.body.appendChild(script);
} else {
const script = document.createElement("script");
script.type = "text/javascript";
script.async = false;
script.innerHTML = scriptToAppend;
document.body.appendChild(script);
}
};
export const removeScript = (scriptToremove) => {
let allsuspects = document.getElementsByTagName("script");
for (let i = allsuspects.length; i >= 0; i--) {
if (
allsuspects[i] &&
allsuspects[i].getAttribute("src") !== null &&
allsuspects[i].getAttribute("src").indexOf(`${scriptToremove}`) !== -1
) {
allsuspects[i].parentNode.removeChild(allsuspects[i]);
}
}
};我将脚本添加到HTML,如下所示:
componentDidMount() {
//Jquery Plugin from the asset site. These are used always.
appendScript("assets/js/jquery-2.2.1.min.js");
appendScript("assets/js/jquery-migrate-1.2.1.min.js");
appendScript("assets/bootstrap/js/bootstrap.min.js");
}尽管其中一个脚本在导航时不能正确加载(通过<Link></Link>组件。
虽然我刷新了页面,但脚本正在工作,我可以看到正在使用的脚本,例如图片正在显示、owl旋转木马和其他可见效果。
分页,我永远不会让脚本在下一页工作,主要是img没有显示。
{pages.map((page) => (
<li key={page} className={page === currentPage ? "active" : "null"}>
<Link to="#" onClick={() => onPageChange(page)}>
{" "}
{page}
</Link>
</li>
))}也许这也是我在React中检索img元素的方式:
<div className="image bg-transfer">
<img src={tag.imagePath} alt="Sorry Can't Find :(" />
</div>为了加载react的脚本,这种方法正确吗?我不能让脚本有太多改变,从静态的HTML草稿转移到React.js。我希望有一个简单的答案...
发布于 2020-10-01 21:31:33
感谢热心的@Tasos Bu,我明白了我错过了什么,他引导我添加了我需要的脚本,如下所示。这解决了我所有的问题(不是全部,仍然不是百万富翁)。这就是我是如何做到的。我正在添加和删除脚本,它仍然使用JQuery的超文本标记语言后,它被呈现。
componentDidMount() {
//All custom Js functions, responsivness etc.
appendScript("assets/js/custom.js");
}
componentDidUpdate() {
//All custom Js functions, responsivness etc.
removeScript("assets/js/custom.js");
appendScript("assets/js/custom.js");
}https://stackoverflow.com/questions/64153690
复制相似问题