Switch.tsx 1.16 KB
import { forwardRef } from 'react';
import type { ButtonHTMLAttributes } from 'react';

import styles from './Switch.module.css';
import { cx } from './utils';

export interface SwitchProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onChange'> {
  /** 受控开关值;组件只通过 onChange 请求变更,不自行持久化业务状态。 */
  checked?: boolean;
  /** loading 表示异步变更中,期间禁用点击并暴露 aria-busy。 */
  loading?: boolean;
  onChange?: (checked: boolean) => void;
}

export const Switch = forwardRef<HTMLButtonElement, SwitchProps>(function Switch(
  { checked = false, className, disabled, loading = false, onChange, type, ...props },
  ref,
) {
  const isDisabled = disabled || loading;

  return (
    <button
      {...props}
      className={cx(styles.switch, checked && styles.checked, loading && styles.loading, className)}
      disabled={isDisabled}
      ref={ref}
      role="switch"
      type={type ?? 'button'}
      aria-checked={checked}
      aria-busy={loading || undefined}
      onClick={() => onChange?.(!checked)}
    >
      <span className={styles.handle} aria-hidden="true" />
    </button>
  );
});