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

如何在Next.js中通过Tailwind CSS使用GraphCMS返回的十六进制颜色

问题描述

我已经通过以下代码从GraphCMS获取分类数据:

import { getCategories } from '../services/graphql';

const [categories, setCategories] = useState([]);

useEffect(() => {
    getCategories()
        .then((result) => setCategories(result));
}, []);

对应的getCategories查询如下:

export const getCategories = async () => {
    const query = gql`
        query GetCategories{
            categories{
                title 
                slug
                metaDesc
                id
                color {
                    hex
                    css
                }
                featuredImage{
                    url
                    height
                    width
                }
            }
        }
    `
    const result = await request(graphqlAPI, query);
    return result.categories;
}

我希望获取分类对应的hex颜色值,用于设置该分类的背景色,请问如何结合Tailwind CSS实现这一需求?

解决方案

Tailwind CSS有两种实用的方式实现这个需求:

方法1:内联style绑定(最直接)

既然已经拿到了分类的color.hex值,直接通过React的内联style属性绑定背景色即可,无需额外配置Tailwind:

{categories.map(category => (
    <div 
        key={category.id}
        className="px-4 py-2 rounded-md text-white"
        style={{ backgroundColor: category.color.hex }}
    >
        {category.title}
    </div>
))}

注意:如果接口返回的hex值不带#前缀(比如ff0000),需要手动补上:style={{ backgroundColor: #${category.color.hex} }}。

方法2:Tailwind JIT动态类名(适配Tailwind工具链)

如果想通过Tailwind类名的方式使用动态颜色,确保你的Tailwind版本是v3(默认开启JIT模式),或者在v2的tailwind.config.js中开启mode: 'jit',之后就可以使用动态背景色类:

{categories.map(category => (
    <div 
        key={category.id}
        className={`px-4 py-2 rounded-md text-white bg-[${category.color.hex}]`}
    >
        {category.title}
    </div>
))}

注意事项:

  • 必须保证category.color.hex包含#前缀,否则Tailwind无法识别该颜色类。
  • 动态类名仅在JIT模式下生效,若未开启,这类动态类会被Tailwind的构建工具忽略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:05:20