如果我在某个组件中多次渲染createGlobalStyle组件会发生什么情况

时间:2019-07-01 06:52:29

标签: styled-components

它将插入几次全局样式,还是在每次卸载后将其清除?

dependencies

1 个答案:

答案 0 :(得分:1)

它将在每次渲染之前清除。仅当组件在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>
      </>
    );
  }
}

相关问题