reactjs - 使用 styled-components 开发组件库时如何使用全局样式

标签 reactjs styled-components

当我使用 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};

`

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

最佳答案

将你的全局样式放在一个文件中,ex: 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;

关于reactjs - 使用 styled-components 开发组件库时如何使用全局样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68900591/

相关文章:

javascript - React 行为触发渲染上的所有按钮

reactjs - 不能给函数组件警告 - 即使将 forwardRef() 与样式组件一起使用

javascript - 为从索引文件导入的 React 组件设置样式时出错,但直接从组件文件导入时则不会

javascript - 样式化组件 - 根据 props 有条件地渲染整个 css block

javascript - 样式组件 : I want to use Variable in Styled-Component

javascript - 使用 styled-components 和 Material-UI withStyles 的 TextField 样式

javascript - 如果我的键类型为数字,为什么 React 会提示我没有唯一的键?

javascript - (JSX) 是 React 中 javascript 的语法扩展是什么意思

javascript - Material-UI formControlLabel 整个标签是可点击的,只有文本应该是

reactjs - React admin 3.x useDataProvider 加载指示器