嗨,我在 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 一起使用的地方使用这个CodeAndSandbox https://codesandbox.io/s/styled-components-with-styled-system-njr17
关于reactjs - 样式组件中的实用程序类 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57411798/