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

如何向Styled Components传递props实现动态样式控制?

问题根因

Styled Components 的样式插值函数只能读取直接挂载在 styled 生成组件上的 props。你的代码里只把mode属性传给了自定义的Header组件,没有继续向下传递给内部的Section styled 组件,Section拿到的props.mode值为undefined,三元判断永远走 false 分支,因此背景色一直显示蓝色。

修复方案

在Header组件内渲染Section时,把接收到的mode属性传给Section即可。

const App = function () {
  const [isDarkMode, setIsDarkMode] = React.useState(true)

  return (
    <main>
      <Header mode={isDarkMode}/>
    </main>
  )
}

const Section = styled.section`
    background-color: ${props => props.mode === true ? "yellow" : "blue"};
    padding: 0 80px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
`

export default function Header (props) {
    return (
        <Section mode={props.mode}>
            <span>Where in the world?</span>
            <FontAwesomeIcon icon={faMoon} />
            <span>DarkMode</span>
        </Section>
    )
}

简化写法

如果 Header 组件本身不需要对传入的 props 做额外处理,可以直接用展开运算符全量透传 props 给 Section,减少重复代码:

export default function Header (props) {
    return (
        <Section {...props}>
            <span>Where in the world?</span>
            <FontAwesomeIcon icon={faMoon} />
            <span>DarkMode</span>
        </Section>
    )
}

内容的提问来源于stack exchange,提问作者Ejovi Okiekpakpo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 20:33:19