Switch
用于通常会立即生效的开启或关闭设置。
预览
实时、可选与锁定设置
切换受控实时价格和邮件提醒,并比较管理员锁定的禁用策略。
安装
首次使用此 Registry?请先完成 基础配置与共享样式安装 。
npx shadcn@latest add @neumorphism-ui/switch先安装一次共享 base,然后使用 CLI 添加组件及其依赖。
实时、可选与锁定设置
npx shadcn@latest add @neumorphism-ui/label @neumorphism-ui/switch用法
将可见 Label 关联到 Switch 的 id。初始值使用 defaultChecked,管理真实设置时将 checked 和 onCheckedChange 连接到应用状态。
"use client";
import { useId } from "react";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
export default function Example() {
const id = useId();
return (
<div className="flex items-center gap-3">
<Switch id={id} name="notifications" defaultChecked />
<Label htmlFor={id}>Email notifications</Label>
</div>
);
}API 参考
在原生 checkbox input 上应用 role=switch,保留表单和浏览器行为。支持 checked、defaultChecked 和 onCheckedChange。
| 组件 | 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|---|
Switch | checked / defaultChecked | boolean | — | 受控的开启状态或非受控初始状态。 |
Switch | onCheckedChange | (checked: boolean) => void | — | 开启状态变化时调用。 |
Switch | onChange | React.ChangeEventHandler<HTMLInputElement> | — | 接收原生 checkbox change event。 |
Switch | disabled | boolean | false | 禁用输入和指针操作。 |
Switch | name / value / required | native input props | — | 用于表单提交的原生 checkbox 属性。 |
无障碍
- 01
由于在真实 checkbox 上使用 role=switch,会向辅助技术传达 Space 键行为和 checked 状态。
- 02
将 Label 的 htmlFor 与 Switch 的 id 关联,或提供 aria-label。
- 03
对于不会立即生效、还需另行保存的 boolean 选择,Checkbox 通常更自然。