问题
I'm currently learning React, and (more importantly) attempting to learn how react actually works.
I have some generated css which I would like to append to head as a style element. In js land, this would be:
const $style = document.createElement("style");
document.head.appendChild($style);
const randBlue = ~~(Math.random() * 250);
$style.innerHtml = `body { color: rgb(10, 10, ${randBlue}); }`;
Unfortunately, in React land, things appear to be a little less straightforward in this regard. My understanding of this is that it is bad practice to append styles to head all willy nilly, because enough people doing it leads to problems. I also recognize that most everybody uses styled-components, glamorous, styled-jsx, or inline for generated css because they circumvent a lot of issues that might come up from the aforementioned willy nillyness.
But I don't want to use modules that I have no understanding of, and as far as I can tell, most of the above create style elements and append them to head somehow, and I would like to know how.
So, if I'm in React and have some generated css text:
const randomColor = Math.random() > 0.5 ? "red" : "blue";
const generatedCss = `body { color: ${randomColor}; }`;
What goes in here?
createStyleElementAndAppendToHead(generatedCss) {
// mystery code
};
回答1:
Welcome to React!
It's true that in react-land there are best practices that people will push onto you like styled-components, glamorous, styled-jsx, inline, etc. And I would even recommend those.
The great part about Reactjs is that vanilla javascript can be used. That same snippet of code can be used in the lifecycle componentDidMount
componentDidMount() {
const $style = document.createElement("style");
document.head.appendChild($style);
const randBlue = ~~(Math.random() * 250);
$style.innerHTML = `body { color: rgb(10, 10, ${randBlue}); }`;
}
Or you can even target the body's inline styles like so:
componentDidMount() {
const randBlue = ~~(Math.random() * 250);
document.body.style.color = `rgb(10, 10, ${randBlue})`;
}
UPDATED for React Hooks:
Put this at at the beginning of your functional component
useEffect(() => {
const randBlue = ~~(Math.random() * 250);
document.body.style.color = `rgb(10, 10, ${randBlue})`;
}, []);
来源:https://stackoverflow.com/questions/48714602/how-can-i-create-a-style-element-and-append-to-head-in-react