【问题标题】:Dynamically loaded CSS in React not working intermittentlyReact 中动态加载的 CSS 不能间歇性工作
【发布时间】:2019-12-15 08:11:32
【问题描述】:

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

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

我试过同时使用linkstyle 标签来加载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


    【解决方案1】:

    我想通了。

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

    做吧。

    【讨论】:

      猜你喜欢
      • 2017-05-02
      • 2012-08-08
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-03
      • 2020-02-04
      相关资源
      最近更新 更多