For AI agents: the complete documentation index is available at https://ifhover.github.io/leaf-ui/llms.txt, the full documentation bundle is available at https://ifhover.github.io/leaf-ui/llms-full.txt, and this page is available as Markdown at https://ifhover.github.io/leaf-ui/components/switch.md.

Switch 开关

即时开启或关闭某项设置。

基础用法

使用开关切换开启和关闭状态,并提供关联名称。

basic.tsx
import { Switch } from '@ifhover/leaf-ui';

export function SwitchBasic() {
  return <Switch>开启通知</Switch>;
}

示例

禁用与加载

disabled 禁用交互。保存期间设置 loading 可阻止重复操作,异步请求由应用处理。

禁用
加载
states.tsx
import { Flex, Grid, Switch, Text } from '@ifhover/leaf-ui';

export function SwitchStates() {
  return (
    <Grid columns={{ xs: 1, sm: 2 }} gap={16} align="center">
      <Text tone="muted">禁用</Text>
      <Flex align="center" wrap>
        <Switch disabled defaultChecked>
          开启通知
        </Switch>
      </Flex>
      <Text tone="muted">加载</Text>
      <Flex align="center" wrap>
        <Switch loading defaultChecked>
          开启通知
        </Switch>
      </Flex>
    </Grid>
  );
}

尺寸

通过 size 设置开关尺寸。

小
中
大
sizes.tsx
import { Flex, Grid, Switch, Text } from '@ifhover/leaf-ui';
import { Fragment } from 'react';

const options = [
  { value: 'sm', label: '小' },
  { value: 'md', label: '中' },
  { value: 'lg', label: '大' },
] as const;

export function SwitchSizes() {
  return (
    <Grid columns={{ xs: 1, sm: 2 }} gap={16} align="center">
      {options.map(({ value, label }) => (
        <Fragment key={value}>
          <Text tone="muted">{label}</Text>
          <Flex align="center" wrap>
            <Switch size={value}>开启通知</Switch>
          </Flex>
        </Fragment>
      ))}
    </Grid>
  );
}

受控状态

通过 checked 控制状态,在 onChange 中从 event.target.checked 读取布尔值。

邮件通知已开启
controlled.tsx
import { Flex, Switch, Text } from '@ifhover/leaf-ui';
import { useState } from 'react';

export function SwitchControlled() {
  const [checked, setChecked] = useState(true);
  return (
    <Flex direction="column" gap="md" align="start">
      <Switch checked={checked} onChange={(event) => setChecked(event.target.checked)}>
        接收邮件
      </Switch>
      <Text tone="muted" role="status">
        {checked ? '邮件通知已开启' : '邮件通知已关闭'}
      </Text>
    </Flex>
  );
}

设置 name 后,已开启且未禁用的开关提交其 value;未开启、禁用或加载时不参与提交。非受控开关在表单重置时恢复 defaultChecked,受控开关需要同步重置应用状态。

API

Switch API

配置开关的选中状态、提交字段与交互状态。

支持 name、value、required、form 等原生 checkbox 属性。通过文字或 aria-label 提供名称;className 和 style 作用于标签容器。

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