reactjs - 样式组件中的实用程序类 react

标签 reactjs styled-components

嗨,我在 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标签中给出精确的样式。但是我怎样才能用像 m-b-10 这样的实用程序类来覆盖这个填充?它会给出 margin-bottom:10px

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

同时我需要随时随地使用这个实用程序类。在 css 中我可以简单地写

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

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

最佳答案

最好的解决方案之一是使用 https://styled-system.com/ ,它与 Styled Components 和其他库(如 Emotion)配合得很好,它提供了您需要的东西,可以在组件定义中使用实用程序类。

例子:

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 with utility functions

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

您可以在与Styled Components 一起使用的地方使用这个CodeAndSandbox https://codesandbox.io/s/styled-components-with-styled-system-njr17

关于reactjs - 样式组件中的实用程序类 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57411798/

相关文章:

javascript - Tiktok.com 和 Youtube shorts 如何自动滚动播放视频(在移动设备上)? react Javascript

ReactJs - 是否可以根据组件树的状态设置 url 或查询字符串

css - react JS : How to use responsive styles with react-spring

reactjs - 无法测试样式为显示 : none 的元素

css - 内部带有固定元素的滚动容器不能在固定元素上滚动

javascript - 没有为 React 按钮设置背景图像

javascript - ReactJS Fetch POST 导致不需要的刷新

javascript - 如何访问ag-grid表数据和详细信息的嵌套对象数组值?

reactjs - 配置故事书文档插件以显示 theme.dark

css - Styled-Components,如何动态生成css属性?