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

ChakraUI:如何设置复选框选中状态下的框体颜色

ChakraUI Checkbox 选中状态框体颜色设置方案

现有组件代码

export function CheckItem({ color, checked, label, onChange }: CheckItemProps) {
  return (
    <Checkbox
      iconColor="white"
      borderColor={color}
      isChecked={checked}
      onChange={onChange}
      size="lg"
    >
      <Text fontSize="12px">{label}</Text>
    </Checkbox>
  );
}

问题描述

如何设置复选框处于选中状态时的框体颜色?已尝试以下方法但均无效:

  • 使用 bg:会设置包含文本在内的整个容器背景色
  • 使用 color:仅修改文本颜色
  • 使用 colorScheme:因使用十六进制颜色值而非主题色,无法生效
  • borderColor:未选中状态正常,但选中后框体恢复默认蓝色填充

期望通过 _checked 属性配置选中状态的样式,代码结构如下:

export function CheckItem({ color, checked, label, onChange }: CheckItemProps) {
  return (
    <Checkbox
      _checked={{
        // 需填写正确属性
      }}
      iconColor="white"
      borderColor={color}
      isChecked={checked}
      onChange={onChange}
      size="lg"
    >
      <Text fontSize="12px">{label}</Text>
    </Checkbox>
  );
}

解决方案

在 _checked 配置中同时设置 bg 和 borderColor 为传入的 color 值即可。ChakraUI 的 Checkbox 选中时,框体的填充色由 bg 控制(此时 bg 仅作用于复选框框体,而非整个容器),同步设置 borderColor 可确保边框与填充色一致,覆盖默认蓝色。

修改后的完整代码:

export function CheckItem({ color, checked, label, onChange }: CheckItemProps) {
  return (
    <Checkbox
      _checked={{
        bg: color,
        borderColor: color
      }}
      iconColor="white"
      borderColor={color}
      isChecked={checked}
      onChange={onChange}
      size="lg"
    >
      <Text fontSize="12px">{label}</Text>
    </Checkbox>
  );
}

内容的提问来源于stack exchange,提问作者Barry Michael Doyle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:32:57