【问题标题】:how can i use global style when develop component library using styled-components使用 styled-components 开发组件库时如何使用全局样式
【发布时间】:2021-08-24 00:54:50
【问题描述】:

当我使用 styled-components 开发我的组件库时,如何使用一种根样式,例如

  box-sizing: border-box;
  outline: 0;
  margin: 0;
  padding: 0;
  border: 0;

在整个库中。

我现在添加全局样式手册,像这样使用 css:

export const global = css`
  box-sizing: border-box;
  outline: 0;
  margin: 0;
  padding: 0;
  border: 0;
`
const RealButton = styled.button`
  ${global};

`

libary 会导出很多组件,我是不是必须在导出每个组件时添加全局样式手册。或者有一个简单的方法来实现它。

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    将您的全局样式放在一个文件中,例如:像这样的 GlobalStyle.js

    import { createGlobalStyle } from 'styled-components';
    const GlobalStyle = createGlobalStyle`
    body {
    box-sizing: border-box;
    outline: 0;
    margin: 0;
    padding: 0;
    border: 0;
    }
    `;
    export default GlobalStyle;
    

    导入你的 GlobalStyle 组件并将它放在你的 React 树的顶部,通常像这样在 app.js 上

    import React, { Fragment } from 'react';
    import GlobalStyle from './globalStyle';
    function App() {
    return (
    <Fragment>
    <GlobalStyle />
    <div>
    My App
    </div>
    </Fragment>
     );
     }
     export default App;
    

    【讨论】:

      猜你喜欢
      • 2021-03-09
      • 1970-01-01
      • 2021-12-28
      • 2021-09-02
      • 1970-01-01
      • 2021-09-19
      • 2019-08-23
      • 2021-06-02
      • 1970-01-01
      相关资源
      最近更新 更多