如果我在某个组件中多次渲染 createGlobalStyle 组件会发生什么
What happens if I render createGlobalStyle component several times inside some component
会多次插入全局样式,还是每次卸载后都会清空?
import {createGlobalStyle} from 'styled-components';
const GlobalStyle = createGlobalStyle`
#some-external-lib-element-that-is-inserted-in-the-end-of-the-body {
color: red;
}
`;
function MyDeepComponent({veryOftenChangingPropThatCausesRerender}) {
return (
<>
<GlobalStyle/>
<SomeExternalLibComponent/>
</>
);
}
每次渲染前都会清除。仅当组件位于 DOM 内时才应用样式。您可以尝试使用以下组件进行测试:
import React from "react";
import {createGlobalStyle} from 'styled-components';
const GlobalStyle = createGlobalStyle`
.global-button {
background: red;
}
`;
export class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
show: true,
};
}
showGlobalStyling = () => {
this.setState((prevState) => ({
show: !prevState.show,
}));
}
render() {
return (
<>
{this.state.show && <GlobalStyle/>}
<button className="global-button" onClick={this.showGlobalStyling} >
click
</button>
</>
);
}
}
会多次插入全局样式,还是每次卸载后都会清空?
import {createGlobalStyle} from 'styled-components';
const GlobalStyle = createGlobalStyle`
#some-external-lib-element-that-is-inserted-in-the-end-of-the-body {
color: red;
}
`;
function MyDeepComponent({veryOftenChangingPropThatCausesRerender}) {
return (
<>
<GlobalStyle/>
<SomeExternalLibComponent/>
</>
);
}
每次渲染前都会清除。仅当组件位于 DOM 内时才应用样式。您可以尝试使用以下组件进行测试:
import React from "react";
import {createGlobalStyle} from 'styled-components';
const GlobalStyle = createGlobalStyle`
.global-button {
background: red;
}
`;
export class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
show: true,
};
}
showGlobalStyling = () => {
this.setState((prevState) => ({
show: !prevState.show,
}));
}
render() {
return (
<>
{this.state.show && <GlobalStyle/>}
<button className="global-button" onClick={this.showGlobalStyling} >
click
</button>
</>
);
}
}