如何在Styled Component中获取传入的CSS对象属性?
在Styled Components中获取传入的CSS对象属性
默认情况下,styled-components自带的css prop是用来给组件追加额外样式的,它不会作为组件的props被直接读取到。不过有两种可行的方式实现你想要的效果:
方法一:直接传自定义属性
这是最直接也最推荐的方式——把需要复用的属性单独作为自定义props传给组件:
const Square = styled.div<{ width: number }>` height: ${props => props.width}px; width: ${props => props.width}px; ` const Component = () => { return ( <> <Square width={100}>test</Square> </> ) }
方法二:把CSS对象作为自定义props传递
如果你确实需要传递完整的CSS对象,可以给它起个自定义名字(比如customCss)当props传入,然后在组件里提取需要的属性:
const Square = styled.div<{ customCss: { width: number } }>` height: ${props => props.customCss.width}px; width: ${props => props.customCss.width}px; ` const Component = () => { return ( <> <Square customCss={{ width: 100 }}>test</Square> </> ) }
注意别搞混内置css prop的作用
styled-components的内置css prop是用来注入额外样式片段的(需要配合css工具函数使用),不是用来传递可读取的属性值的。举个例子:
import { css } from 'styled-components'; const redBg = css` background-color: red; ` // 这里的css prop是给Square加红色背景,没法通过props.css访问里面的属性 <Square css={redBg}>test</Square>
内容的提问来源于stack exchange,提问作者Artem Isachenkov
相关产品推荐
相关产品推荐

