Switch.tsx

Switch.tsx

基本信息

  • 类型: React 组件 (shadcn/ui)
  • 路径: ./src/components/ui/switch.tsx

功能描述

开关组件,用于切换两种状态(开/关)。基于 Radix UI,支持无障碍访问。

导出内容

  • Switch - 开关组件

Props 接口

Switch

属性类型必填默认值说明
checkedboolean-是否选中(受控)
defaultCheckedboolean-默认是否选中(非受控)
onCheckedChange(checked: boolean) => void-状态变化回调
disabledboolean-是否禁用
classNamestring-自定义CSS类名
...propsReact.ComponentProps<typeof SwitchPrimitive.Root>-Radix Switch 属性

依赖

  • @radix-ui/react-switch - Radix UI 开关原语
  • @/lib/utils - 工具函数 (cn)

使用示例

import { Switch } from "@/components/ui/switch";
import { useState } from "react";

// 非受控组件
<Switch defaultChecked />

// 受控组件
const [checked, setChecked] = useState(false);
<Switch checked={checked} onCheckedChange={setChecked} />

// 带标签
<div className="flex items-center space-x-2">
  <Switch id="airplane-mode" />
  <Label htmlFor="airplane-mode">飞行模式</Label>
</div>

// 禁用状态
<Switch disabled />
<Switch disabled checked />

// 在 Form 中使用
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
  <div className="space-y-0.5">
    <FormLabel className="text-base">营销邮件</FormLabel>
    <FormDescription>
      接收关于新功能和产品更新的邮件。
    </FormDescription>
  </div>
  <FormControl>
    <Switch
      checked={field.value}
      onCheckedChange={field.onChange}
    />
  </FormControl>
</FormItem>
← 返回目录