gpt4 book ai didi

javascript - React 中动态加载的 CSS 无法间歇性工作

转载 作者:行者123 更新时间:2023-11-28 19:20:27 25 4
gpt4 key购买 nike

我在 React 中制作了一个“可插入”系统,它动态运行由 HTML、JS 和 CSS 文件组成的微型“应用程序”。 HTML 和 CSS 文件是可选的。它们通过窗口对象相互通信。

我正在此处动态加载这三个文件,但我遇到的问题是我的 CSS 类在 1/5 的时间内无法正常工作。它们甚至似乎都没有被解析,因为我也无法在 Chrome devtools 中手动应用它们。

我试过同时使用 linkstyle 标签来加载 CSS,但两者都有同样的问题。即使 CSS 和 HTML 注入(inject)之间的 1000 毫秒 setTimeout 也无济于事。大约每三次组件安装时,CSS 解析就会持续失败。

我试过 Chrome、Firefox 和 Safari。这三个问题都一样。

我有点卡住了,我很想得到一些关于这个的反馈..

这是问题的视频:(这里的“应用程序”是一个简单的 SVG 文件查看器)http://www.giphy.com/gifs/dvHjBBolgA1xAdyRsv

  const windowInitialized = useElementBlockInitialization({
id: elementBlockID,
payload: payload,
onResult: onResult
});
const [styleAndHTMLInitialized, setStyleAndHTMLInitialized] = useState(false);

// after some properties are set in Window, run this effect
useEffect(() => {
let gettingStyleAndHTML = false;
if (windowInitialized) {
gettingStyleAndHTML = true;
getStyleAndHTML().then(({ styleBody, htmlBody }) => { // async function that fetches some html and css as a string (both potentially null)
if (gettingStyleAndHTML) {
if (styleBody) {
const styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.appendChild(document.createTextNode(styleBody));
document.head.appendChild(styleElement);
}
if (htmlBody) {
// containerElement is a ref
containerElement.current.innerHTML = htmlBody;
}
setStyleAndHTMLInitialized(true);
}
});
}
return () => {
gettingStyleAndHTML = false;
};
}, [windowInitialized]);

// after the CSS and HTML is injected, run this hook
useEffect(() => {
if (styleAndHTMLInitialized) {
const scriptElement = document.createElement('script');
scriptElement.setAttribute('data-eb-container-id', containerElementID);
scriptElement.setAttribute('data-eb-id', elementBlockID);
scriptElement.setAttribute('src', makeElementBlockBaseURL() + '.js');
document.head!.appendChild(scriptElement);

return () => {
scriptElement.remove();
};
}
return;
}, [styleAndHTMLInitialized]);

// only render the container once the window properties are set
return windowInitialized ? (
<Container ref={containerElement} id={containerElementID} />
) : null;

最佳答案

我想通了。

我自动生成的类名有时以数字开头。 CSS 类名显然不能以数字开头!

做吧。

关于javascript - React 中动态加载的 CSS 无法间歇性工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57398644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com