Textarea.tsx
1.99 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
55
56
57
58
59
60
61
62
63
64
65
66
import { forwardRef, useState } from 'react';
import type { TextareaHTMLAttributes } from 'react';
import styles from './Textarea.module.css';
import { cx } from './utils';
export interface TextareaProps extends Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, 'onChange' | 'size'> {
/** 状态样式用于和 FormItem 校验信息协同展示。 */
status?: 'default' | 'success' | 'warning' | 'error';
/** 是否显示输入长度,默认使用简洁的当前值/上限格式。 */
showCount?: boolean;
onChange?: (value: string) => void;
}
export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(function Textarea(
{
className,
defaultValue,
disabled,
onChange,
rows = 4,
showCount = false,
status = 'default',
value,
...props
},
ref,
) {
const [innerValue, setInnerValue] = useState(defaultValue?.toString() ?? '');
const currentValue = value === undefined ? innerValue : String(value);
const emitChange = (nextValue: string) => {
if (value === undefined) {
setInnerValue(nextValue);
}
onChange?.(nextValue);
};
// 多行输入的长度提示放在右下角,既不挤压正文,也能保持简洁可扫读。
const countLabel = props.maxLength !== undefined ? `${currentValue.length}/${props.maxLength}` : String(currentValue.length);
return (
<span
className={cx(
styles.field,
status === 'error' && styles.fieldError,
status === 'warning' && styles.fieldWarning,
status === 'success' && styles.fieldSuccess,
disabled && styles.fieldDisabled,
className,
)}
>
<textarea
{...props}
ref={ref}
className={styles.textarea}
disabled={disabled}
rows={rows}
value={currentValue}
aria-invalid={status === 'error' || undefined}
onChange={(event) => emitChange(event.target.value)}
/>
{showCount ? <span className={styles.footer}>{countLabel}</span> : null}
</span>
);
});