45 lines
1.0 KiB
TypeScript
45 lines
1.0 KiB
TypeScript
import styles from './Switch.module.css'
|
|
|
|
/**
|
|
* 开关:设置项的即时生效开关。
|
|
*
|
|
* 原生 `button` + `role="switch"`,空格/回车都能切换;
|
|
* 没有可见文字标签时,`label` 必填(进 aria-label)。
|
|
*/
|
|
export type SwitchSize = 'sm' | 'md'
|
|
|
|
export type SwitchProps = {
|
|
checked: boolean
|
|
onChange: (checked: boolean) => void
|
|
disabled?: boolean
|
|
size?: SwitchSize
|
|
/** 无障碍名称:开关旁边没有文字时必填 */
|
|
label?: string
|
|
className?: string
|
|
}
|
|
|
|
export function Switch({
|
|
checked,
|
|
onChange,
|
|
disabled = false,
|
|
size = 'md',
|
|
label,
|
|
className,
|
|
}: SwitchProps) {
|
|
return (
|
|
<button
|
|
type="button"
|
|
role="switch"
|
|
aria-checked={checked}
|
|
aria-label={label}
|
|
disabled={disabled}
|
|
className={[styles.root, styles[size], checked ? styles.on : undefined, className]
|
|
.filter(Boolean)
|
|
.join(' ')}
|
|
onClick={() => onChange(!checked)}
|
|
>
|
|
<span className={styles.thumb} aria-hidden="true" />
|
|
</button>
|
|
)
|
|
}
|