我目前正在学习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领域,这方面的事情似乎不那么简单。我对此的理解是,随意地将样式附加到head是一种糟糕的做法,因为有足够多的人这样做会导致问题。我还认识到,大多数人都使用样式组件、迷人的样式jsx或内联生成的css,因为它们避开了前面提到的nillyness可能出现的许多问题。
但我不想使用我不了解的模块,据我所知,上面的大多数模块都创建了样式元素,并以某种方式将它们附加到head中,我想知道如何创建。
所以,如果我在React中生成了一些css文本:
const randomColor = Math.random() > 0.5 ? "red" : "blue";
const generatedCss = `body { color: ${randomColor}; }`;这里面放了什么?
createStyleElementAndAppendToHead(generatedCss) {
// mystery code
};发布于 2018-02-10 05:57:41
欢迎加入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}); }`;
}或者,您甚至可以像这样针对body的内联样式:
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})`;
}, []);https://stackoverflow.com/questions/48714602
复制相似问题