[React] Use react styled system with styled components
In this lesson we’ll improve a generic button primitive component by refactoring it with Styled System to simplify the implementation.
The naïve styled-component implementation has styles like this:
import styled from 'styled-components'
export const Button = styled.button`
width: ${(props) => (props.fullWidth ? '100%' : undefined)};
padding: 8px 16px;
background-color: ${(props) =>
props.variant === 'primary'
? props.theme.colors.primary
: props.theme.colors.secondary};
color: snow;
border: 0;
border-radius: 0.2rem;
font-size: 1rem;
cursor: pointer;
&:hover,
&:active {
background-color: ${(props) => props.theme.colors.accent};
}
&:focus {
outline: 0;
box-shadow: 0 0 0 2px white, 0 0 0 4px salmon;
}
@media (max-width: 550px) {
width: 100%;
}
`
Button.propTypes = {
variant: PropTypes.oneOf(['secondary', 'primary']),
}
Button.defaultProps = {
variant: 'secondary',
}
Convert to Style system:
import styled, { ThemeProvider } from 'styled-components'
import css from '@styled-system/css'
import { variant, space } from 'styled-system'
const variants = {
primary: {
color: 'background',
backgroundColor: 'primary',
},
secondary: {
color: 'primary',
backgroundColor: 'background',
},
}
const Button = styled.button(
css({
boxSizing: 'border-box',
display: 'inline-block',
textAlign: 'center',
px: 4,
py: 3,
color: (props) => (props.variant === 'primary' ? 'background' : 'primary'),
backgroundColor: (props) =>
props.variant === 'primary' ? 'primary' : 'background',
border: '1px solid',
borderColor: 'primary',
borderRadius: 'round',
fontFamily: 'body',
fontSize: 'm',
textDecoration: 'none',
'&:hover:not(:disabled),&:active:not(:disabled),&:focus': {
outline: 0,
color: 'background',
borderColor: 'accent',
backgroundColor: 'accent',
cursor: 'pointer',
},
'&:disabled': {
opacity: 0.6,
filter: 'saturate(60%)',
},
}),
variant({ variants }),
space,
)
export default Button
Use:
<Button p="10 20" fullWidth variant="primary"> Click Me </Button>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2019-08-23 [Cypress] install, configure, and script Cypress for JavaScript web applications -- part4
2018-08-23 [Debug] Inspect and Style an Element in DevTools that Normally Disappears when Inactive
2017-08-23 [Web Security] JSON Hijacking
2017-08-23 [Angular] Progress HTTP Events with 'HttpRequest'
2017-08-23 [RxJS] How To get the results of two HTTP requests made in sequence
2017-08-23 [RxJS] Avoid mulit post requests by using shareReplay()
2017-08-23 [Angular] Http Custom Headers and RequestOptions