【问题标题】:How can I create a style element and append to head in React?如何在 React 中创建样式元素并附加到头部?
【发布时间】:2018-07-20 17:47:58
【问题描述】:

我目前正在学习 React,并且(更重要的是)尝试了解 React 的实际工作原理。

我有一些生成的 css,我想将其作为样式元素附加到头部。在 js 领域,这将是:

const $style = document.createElement("style");
document.head.appendChild($style);
const randBlue = ~~(Math.random() * 250);
$style.innerHtml = `body { color: rgb(10, 10, ${randBlue}); }`;

不幸的是,在 React 领域,这方面的事情似乎不太直接。我对此的理解是,随意添加样式是不好的做法,因为这样做的人太多会导致问题。我还认识到,大多数人都使用 styled-components、glamorous、styled-jsx 或 inline 来生成 css,因为它们规避了很多可能因上述任性而产生的问题。

但是我不想使用我不了解的模块,据我所知,上面的大多数都创建了样式元素并以某种方式将它们附加到头部,我想知道如何。

所以,如果我在 React 中并且有一些生成的 css 文本:

const randomColor = Math.random() > 0.5 ? "red" : "blue";
const generatedCss = `body { color: ${randomColor}; }`;

这里有什么?

createStyleElementAndAppendToHead(generatedCss) {
  // mystery code
};

【问题讨论】:

    标签: css reactjs html-head


    【解决方案1】:

    欢迎来到反应!

    确实,在 react-land 中,人们会向您推荐一些最佳实践,例如 styled-components、glamorous、styled-jsx、inline 等。我什至会推荐这些。

    关于 Reactjs 的伟大之处在于可以使用原生 javascript。在生命周期中可以使用相同的 sn-p 代码componentDidMount

    componentDidMount() {
      const $style = document.createElement("style");
      document.head.appendChild($style);
      const randBlue = ~~(Math.random() * 250);
      $style.innerHTML = `body { color: rgb(10, 10, ${randBlue}); }`;
    }
    

    或者你甚至可以像这样定位正文的内联样式:

    componentDidMount() {
      const randBlue = ~~(Math.random() * 250);
      document.body.style.color = `rgb(10, 10, ${randBlue})`;
    }
    

    为 React Hooks 更新:

    把它放在功能组件的开头

    useEffect(() => {
      const randBlue = ~~(Math.random() * 250);
      document.body.style.color = `rgb(10, 10, ${randBlue})`;
    }, []);
    

    【讨论】:

    • 打败我。记得清理componentWillUnmount中的样式。
    • 很好的答案。请改成$style.innerHTML。
    猜你喜欢
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 2013-12-13
    • 2012-10-06
    • 1970-01-01
    • 2012-10-29
    相关资源
    最近更新 更多