Checkbox.tsx
1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { forwardRef, useEffect, useRef } from 'react';
import type { InputHTMLAttributes, ReactNode } from 'react';
import styles from './Checkbox.module.css';
import { cx } from './utils';
export interface CheckboxProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'type'> {
/** 复选框右侧文本,保持 label 包裹以扩大可点击区域。 */
label?: ReactNode;
/** 半选态用于树、表格批量选择等父子级选择场景。 */
indeterminate?: boolean;
onChange?: (checked: boolean) => void;
}
export const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(function Checkbox(
{ checked, className, disabled, indeterminate = false, label, onChange, ...props },
forwardedRef,
) {
const innerRef = useRef<HTMLInputElement | null>(null);
const accessibleLabel = typeof label === 'string' ? label : props['aria-label'];
useEffect(() => {
if (innerRef.current) {
innerRef.current.indeterminate = indeterminate;
}
}, [indeterminate]);
return (
<label className={cx(styles.label, disabled && styles.labelDisabled, className)}>
<input
{...props}
ref={(node) => {
innerRef.current = node;
if (typeof forwardedRef === 'function') {
forwardedRef(node);
} else if (forwardedRef) {
forwardedRef.current = node;
}
}}
className={styles.input}
checked={checked}
disabled={disabled}
type="checkbox"
aria-label={accessibleLabel}
aria-checked={indeterminate ? 'mixed' : checked}
onChange={(event) => onChange?.(event.target.checked)}
/>
<span className={cx(styles.box, indeterminate && styles.mixed)} aria-hidden="true">
{indeterminate ? '−' : checked ? '✓' : null}
</span>
{label}
</label>
);
});