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

如何在自定义组件中使用antd theme tokens?

使用Ant Design主题Token为自定义组件设置样式:类似Emotion的实现及优化方案

一、类似Emotion的CSS-in-JS实现方式

你给出的createStyles示例其实就是Ant Design官方提供的、类似Emotion的CSS-in-JS方案(基于@ant-design/cssinjs包),它支持直接在JS中编写样式并注入主题Token,和Emotion的使用逻辑高度相似。

修正语法错误后的完整代码如下:

// style.ts
import { createStyles } from '@ant-design/cssinjs';

export default createStyles((token) => ({
  foo: {
    color: token.colorPrimary,
    fontSize: token.fontSizeLG,
    padding: token.paddingMD,
  },
}));
// index.tsx
import styles from './style';
import { ConfigProvider } from 'antd';

const FooBar = () => {
  const { className } = styles.useStyle();
  return (
    <div className={className.foo}>
      FooBar
    </div>
  );
};

// 需在全局ConfigProvider下使用,确保主题Token生效
export default () => (
  <ConfigProvider>
    <FooBar />
  </ConfigProvider>
);

这个方案的核心是createStyles定义样式规则,通过useStyle钩子在组件中生成实际类名,和Emotion的styled或css函数逻辑一致,且能自动同步Ant Design的主题配置。

二、更优的实现方案

除了createStyles,还有几种更灵活的方案适配不同场景:

1. useToken结合第三方CSS-in-JS库(如Emotion)

如果项目已使用Emotion,可直接用useToken获取主题Token,在Emotion组件中复用:

import { useToken } from 'antd';
import styled from '@emotion/styled';

const FooBarWrapper = styled.div`
  color: ${({ token }) => token.colorPrimary};
  font-size: ${({ token }) => token.fontSizeLG}px;
  padding: ${({ token }) => token.paddingMD}px;
`;

const FooBar = () => {
  const { token } = useToken();
  return <FooBarWrapper token={token}>FooBar</FooBarWrapper>;
};

2. 使用useStyleRegister实现底层样式控制

useStyleRegister是@ant-design/cssinjs提供的底层钩子,适合需要自定义样式注册逻辑的场景:

import { useStyleRegister, useToken } from '@ant-design/cssinjs';

const FooBar = () => {
  const { token, hashId } = useToken();

  const className = useStyleRegister(
    { theme: token, hashId, path: ['FooBar'] },
    () => [
      {
        '.foo': {
          color: token.colorPrimary,
          fontSize: token.fontSizeLG,
          padding: token.paddingMD,
        },
      },
    ]
  );

  return <div className={`${className} foo`}>FooBar</div>;
};

3. 全局CSS变量注入(轻量化方案)

开启Ant Design的CSS变量功能后,可直接在样式中用原生CSS变量复用主题Token,无需引入CSS-in-JS库:

import { ConfigProvider } from 'antd';
import type { ThemeConfig } from 'antd';

const theme: ThemeConfig = {
  token: {
    colorPrimary: '#1890ff',
  },
  cssVar: true, // 开启全局CSS变量注入
};

const FooBar = () => {
  return (
    <div style={{ color: 'var(--ant-color-primary)' }}>
      FooBar
    </div>
  );
};

export default () => (
  <ConfigProvider theme={theme}>
    <FooBar />
  </ConfigProvider>
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 18:05:22