Radio.tsx 1.17 KB
import { forwardRef } from 'react';
import type { InputHTMLAttributes, ReactNode } from 'react';

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

export interface RadioProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'type'> {
  /** 单选项文本,业务侧通过相同 name 组合出互斥选择组。 */
  label?: ReactNode;
  onChange?: (value: string) => void;
}

export const Radio = forwardRef<HTMLInputElement, RadioProps>(function Radio(
  { className, disabled, label, onChange, value, ...props },
  ref,
) {
  const accessibleLabel = typeof label === 'string' ? label : props['aria-label'];

  return (
    <label className={cx(styles.label, disabled && styles.labelDisabled, className)}>
      <input
        {...props}
        ref={ref}
        className={styles.input}
        disabled={disabled}
        type="radio"
        value={value}
        aria-label={accessibleLabel}
        onChange={() => undefined}
        onClick={() => {
          if (!disabled) {
            onChange?.(String(value ?? ''));
          }
        }}
      />
      <span className={styles.dot} aria-hidden="true" />
      {label}
    </label>
  );
});