样式组件中的实用程序 类 React

utility classes in styled component react

嗨,我在 React 中使用样式化组件

const H4 = styled.h4`
  font-size: 15px;
  letter-spacing: 0.38px;
  line-height: 1.33;
  color: red;
  padding: 20px;
`;

<H4>Small header</H4>

它将在H4标签中给出精确的样式。但是我怎样才能用 classes 这样的实用程序覆盖这个填充 m-b-10 它会给 margin-bottom:10px

像这样<H4 m-b-10>small header</H4>

同时我需要随时随地使用此实用程序class。在 css 我可以简单地写

m-b-10{margin-bottom:10px !important};

如何在样式组件上实现这些东西?

您可以使用像

这样的变量
const m-b-10 = '20px';
const H4 = styled.h4`
   padding: ${m-b-10};
`;

您可以在单独的文件中定义此类变量并将它们导入到样式组件中

最好的解决方案之一是使用 https://styled-system.com/,它可以很好地与 Styled ComponentsEmotion 等其他库配合使用它提供了你所需要的,在组件定义中使用 utility-类。

示例:

import styled from 'styled-components'
import { color, space, fontSize } from 'styled-system'

// Set default styles and add styled-system functions to your component
const Box = styled.div`

  /*defaut styles */
  color: white;
  font-size: 25px;
  padding: 20px;

  /* configurable properties */;
  ${color};
  ${space};
  ${fontSize};

`;

并使用它:

  <Box bg="black" >
    Lorem Ipsum
  </Box>  

  <Box bg="black" color="green" fontSize="12px" p="10px">
    Lorem Ipsum
  </Box>

该代码将呈现以下内容:

它还支持媒体查询、主题等。

您可以在与 Styled Components https://codesandbox.io/s/styled-components-with-styled-system-njr17

一起使用的地方玩这个 CodeAndSandbox

您可以在 React 树的顶部组件中定义实用程序 类。该示例使用 Gatsby.js,但您可以轻松地将其改编为其他 React 框架。

// src/components/layout.js
const GlobalStyles = createGlobalStyles`
  html {
    /* Put your CSS variables here*/
  }
  .m-b-10 {
    margin-bottom: 10px;
  }
`

然后使 createGlobalStyles 中定义的内容可用于子组件中的访问。

// src/components/layout.js
export default function Layout({ children }) {
  return (
    <React.Fragment>
      <GlobalStyle />
      {children}
    </React.Fragment>
  )
}
// src/pages.index.js
import Layout from "../components/layout"
const H4 = styled.h4`
  font-size: 15px;
  letter-spacing: 0.38px;
  line-height: 1.33;
  color: red;
  padding: 20px;
`;
const IndexPage = () => {
  return (
    <Layout>
      <H4 className="m-b-10" />
    </Layout>
  )
}