You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 02:37:29