Radio Group

用于从少量可见选项中选择唯一的值。

预览

显示密度

从带有辅助说明的 Compact、Comfortable 和 Spacious 三种密度中选择。

安装

首次使用此 Registry?请先完成 基础配置与共享样式安装 。

npx shadcn@latest add @neumorphism-ui/radio-group

先安装一次共享 base,然后使用 CLI 添加组件及其依赖。

显示密度

npx shadcn@latest add @neumorphism-ui/label @neumorphism-ui/radio-group
Registry JSON

用法

为组提供名称,为每个 RadioGroupItem 提供唯一 value 和可见标签。使用 defaultValue 设置初始值,或结合 onValueChange 控制选择。

"use client";

import { useId } from "react";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";

export default function Example() {
  const id = useId();
  return (
    <RadioGroup defaultValue="standard" aria-label="Delivery method">
      <Label htmlFor={id + "-standard"} className="flex items-center gap-2">
        <RadioGroupItem id={id + "-standard"} value="standard" />Standard
      </Label>
      <Label htmlFor={id + "-express"} className="flex items-center gap-2">
        <RadioGroupItem id={id + "-express"} value="express" />Express
      </Label>
    </RadioGroup>
  );
}

API 参考

通过 React context 共享 name 和选中状态,同时每个项目都渲染为真实的 input[type=radio]。支持受控与非受控值、横向和纵向排列、disabled 及 required。

组件属性类型默认值说明
RadioGroupvalue / defaultValuestring—受控的选中值或非受控初始值。
RadioGrouponValueChange(value: string) => void—选中值变化时调用。
RadioGrouporientation"horizontal" | "vertical""vertical"设置排列方向和 aria-orientation。
RadioGroupnamestringgenerated id各项目共享的原生 radio name。
RadioGroupdisabled / requiredbooleanfalse设置所有项目的输入限制。
RadioGroupItemvalue必填string—项目被选中时传给组合的值。

无障碍

  • 01

    在 RadioGroup 根元素上通过 aria-label 或 aria-labelledby 提供整个组合的名称。

  • 02

    将每个 RadioGroupItem 的 id 与 Label 的 htmlFor 关联。

  • 03

    由于使用真实的 radio input,会保留浏览器表单提交和键盘选择行为。