switch.md
组件 · COMPONENT

开关 Switch

墨色开关:关闭是浅灰轨道,开启是墨色轨道,白色滑块沿标准缓动滑过去。

点一下试试
import { useState } from 'react'
import { Switch } from './extracted/Switch.jsx'

export default function SwitchDemo() {
  const [on, setOn] = useState(true)
  return (
    <div style={{ display: 'flex', gap: 32, flexWrap: 'wrap', alignItems: 'center' }}>
      <Switch id="sw-notify" checked={on} onChange={setOn} label={on ? '已开启' : '已关闭'} />
      <Switch id="sw-locked" disabled label="禁用" />
    </div>
  )
}
三种状态
import { Switch } from './extracted/Switch.jsx'

export function States() {
  return (
    <>
      <Switch id="s-on" checked label="已开启" />
      <Switch id="s-off" label="已关闭" />
      <Switch id="s-dis" disabled label="禁用" />
    </>
  )
}

属性

属性取值默认说明
checkedbooleanfalse是否开启(受控)
onChange(next: boolean) => void切换回调
disabledbooleanfalse禁用:更浅的轨道 + 60% 透明
labelstring右侧文字;缺省时读屏名为「开关」
idstring关联 label 的 for

说明

尺寸 42×25、滑块偏移 2.5 是 edu 样张的原值,为了 1:1 保留,不在 4pt 梯上。它在 edu 里只以后台样张存在,这里提炼成组件,本站是它的源头。