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

如何使用vanilla-extract和TypeScript动态设置按钮背景色

问题描述

我希望使用vanilla-extract和TypeScript动态设置按钮的背景色,初始示例代码如下:

button.tsx

import {buttonStyle} from './button.css.ts'
const Button = ({backgroundColor}) => {
  return (
    <button className={buttonStyle}>button</button>
  )
}

button.css.ts

import { style } from '@vanilla-extract/css';
export const buttonStyle = style({
    width: '100%',
    backgroundColor: ?
});

我尝试了以下写法,但出现报错:

修改后的button.tsx

import {buttonStyle} from './button.css.ts'
const Button = ({backgroundColor}) => {
  return (
    <button className={buttonStyle(backgroundColor)}>button</button>
  )
}

修改后的button.css.ts

import { style } from '@vanilla-extract/css';
export const buttonStyle = (backgroundColor) => style({
    width: '100%',
    backgroundColor: backgroundColor
});

报错信息

storybook: You can only export plain objects, arrays, strings, numbers and null/undefined.null/undefined.
storybook: Plugin: vanilla-extract

请问该如何正确实现动态设置按钮背景色?


解决方案

vanilla-extract是静态CSS提取工具,不支持在运行时动态生成样式函数(这就是你报错的核心原因——它要求.css.ts文件导出静态值,不能导出函数)。下面提供两种合法的实现方式:

方法一:使用CSS变量(支持任意自定义颜色)

适合需要接受任意颜色值的场景:

  1. 在button.css.ts中定义使用CSS变量的基础样式
import { style } from '@vanilla-extract/css';

export const buttonStyle = style({
  width: '100%',
  backgroundColor: 'var(--button-bg, #ccc)' // 可设置默认背景色
});
  1. 在组件中通过style属性传递CSS变量
import { buttonStyle } from './button.css.ts';

type ButtonProps = {
  backgroundColor?: string;
};

const Button = ({ backgroundColor }: ButtonProps) => {
  return (
    <button
      className={buttonStyle}
      style={backgroundColor ? { '--button-bg': backgroundColor } : {}}
    >
      button
    </button>
  );
};

export default Button;

方法二:使用styleVariants(适合预定义颜色集合)

如果按钮背景色只有固定几种选项,推荐这种方式,vanilla-extract会提前生成所有变体的CSS类:

  1. 在button.css.ts中定义样式变体
import { style, styleVariants } from '@vanilla-extract/css';

// 基础通用样式
const baseButton = style({
  width: '100%'
});

// 预定义背景色变体
export const buttonStyle = styleVariants({
  primary: [baseButton, { backgroundColor: '#0070f3' }],
  secondary: [baseButton, { backgroundColor: '#6e7681' }],
  danger: [baseButton, { backgroundColor: '#ff4d4f' }]
});
  1. 在组件中传入预定义的变体名称
import { buttonStyle } from './button.css.ts';

type ButtonProps = {
  variant: keyof typeof buttonStyle;
};

const Button = ({ variant }: ButtonProps) => {
  return (
    <button className={buttonStyle[variant]}>
      button
    </button>
  );
};

export default Button;

// 使用示例:<Button variant="primary" />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 22:16:03