You need to enable JavaScript to run this app. 如何在styled-components中使用JSON对象属性实现条件样式渲染?
优惠活动
大模型
产品
解决方案
定价
更多

如何在styled-components中使用JSON对象属性实现条件样式渲染?

实现方案

直接在条件判断的回调函数内引用已导入的colors对象取值即可,styled-components的模板字符串内的函数可以直接访问当前文件的全局变量,无需额外配置。

修改后的styles.js完整代码如下:

import styled from 'styled-components'
import { colors } from './colored.json'

const Tabs = styled.button`    
 background-color: ${props => props.active ? colors['Brand/PrimaryBlack'] : colors['Brand/PrimaryGreen']};
`

注意事项

  • 如果运行时出现JSON解析报错,可以删除colored.json中"Brand/PrimaryGreen": "#8ED6C9",末尾的多余逗号,部分低版本打包工具不支持JSON尾逗号语法

内容的提问来源于stack exchange,提问作者Federick J

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 01:39:01