Textarea.tsx 1.99 KB
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>
  );
});