如何在React中创建样式元素并追加?

Sep*_*eed 7 css html-head reactjs

我正在学习React,并且(更重要的是)试图了解反应是如何实际运作的.

我有一些生成的CSS,我想作为样式元素追加到头部.在js land中,这将是:

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

不幸的是,在React的土地上,事情在这方面似乎不太直白.我对此的理解是,将所有样式添加到willy nilly是不好的做法,因为有足够的人做这件事会导致问题.我也认识到大多数人都使用样式组件,魅力四射,样式化的jsx,或内联生成的CSS,因为它们可以避免上述威利猥亵可能产生的许多问题.

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

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

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

这里有什么?

createStyleElementAndAppendToHead(generatedCss) {
  // mystery code
};
Run Code Online (Sandbox Code Playgroud)

Cra*_*123 6

欢迎使用React!

的确,在React-land中,人们会向您推荐最佳实践,例如样式组件,迷人的样式,jsx样式,内联等。我什至会推荐那些。

关于Reactjs的很大一部分是可以使用原始javascript。可以在生命周期中使用相同的代码片段componentDidMount

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

或者,您甚至可以像这样针对身体的内联样式:

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

为React Hooks更新:

将其放在功能组件的开头

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