【发布时间】:2019-12-15 08:11:32
【问题描述】:
我在 React 中制作了一个“可插拔”系统,它可以动态运行由 HTML、JS 和 CSS 文件组成的微型“应用程序”。 HTML 和 CSS 文件是可选的。它们通过 window 对象相互通信。
我在这里动态加载这三个文件,但我遇到的问题是我的 CSS 类在 1/5 的时间里无法工作。它们甚至似乎都没有被解析,因为我也无法在 Chrome 开发工具中手动应用它们。
我试过同时使用link 和style 标签来加载CSS,但都有同样的问题。即使是 CSS 和 HTML 注入之间的 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;
【问题讨论】:
标签: javascript css reactjs react-hooks