For AI agents: the complete documentation index is available at https://ifhover.github.io/leaf-ui/v/0.6.0/llms.txt, the full documentation bundle is available at https://ifhover.github.io/leaf-ui/v/0.6.0/llms-full.txt, and this page is available as Markdown at https://ifhover.github.io/leaf-ui/v/0.6.0/components/switch.md.
  • 简体中文
  • Switch 开关

    用于即时开启或关闭某个设置。

    基础状态

    loading 显示加载图标并阻止交互,可用于异步保存期间避免重复操作。

    basic.tsx
    import { Space, Switch } from '@ifhover/leaf-ui';
    
    export function SwitchBasic() {
      return (
        <Space wrap>
          <Switch defaultChecked>开启通知</Switch>
          <Switch>自动保存</Switch>
          <Switch disabled defaultChecked>
            已锁定
          </Switch>
          <Switch loading>正在保存设置</Switch>
        </Space>
      );
    }
    

    受控与尺寸

    通过 checked / onChange 管理开关状态,size 调整大小。

    邮件通知已开启
    controlled.tsx
    import { Flex, Space, Switch, Text } from '@ifhover/leaf-ui';
    
    import { useState } from 'react';
    
    export function SwitchControlled() {
      const [checked, setChecked] = useState(true);
      return (
        <Space direction="vertical" align="stretch">
          <Switch checked={checked} onChange={(event) => setChecked(event.target.checked)}>
            接收邮件
          </Switch>
          <Text tone="muted" aria-live="polite">
            {checked ? '邮件通知已开启' : '邮件通知已关闭'}
          </Text>
          <Flex gap="md" align="center" wrap justify="center">
            <Switch size="sm" defaultChecked>
              小尺寸
            </Switch>
            <Switch defaultChecked>默认尺寸</Switch>
            <Switch size="lg" defaultChecked>
              大尺寸
            </Switch>
          </Flex>
        </Space>
      );
    }
    

    Switch API

    属性类型默认值说明
    checked / defaultCheckedboolean—受控状态 / 非受控初始状态
    onChangeChangeEventHandler<HTMLInputElement>—从 event.target.checked 读取开关状态
    size'sm' | 'md' | 'lg''md'开关尺寸
    loadingbooleanfalse显示加载状态并禁用交互
    disabledbooleanfalse禁用交互
    childrenReactNode—可点击的文字标签
    refRef<HTMLInputElement>—开关引用

    支持 name、value、required、form 等原生属性。未开启或被禁用的开关不参与原生表单提交。没有文字时使用 aria-label;className 与 style 作用于标签容器。

    类型

    可导入 SwitchProps 定义组件属性,或使用尺寸类型:

    import type { SwitchProps, ControlSize } from '@ifhover/leaf-ui';