如何封装兼容两种模式的自定义 Input 组件

解读

“两种模式”在国内面试语境里通常指:

  1. 受控模式(controlled):值由父级 state 托管,组件只负责渲染与回调。
  2. 非受控模式(uncontrolled):值由组件内部 ref/state 托管,父级只在需要时一次性读取(如提交表单)。

面试官想考察:

  • 对受控与非受控本质区别的理解(数据主权归属)。
  • 在单组件内同时支持两种模式,且 API 一致、零门槛切换。
  • 边界处理:默认值、受控判定的时机、TypeScript 类型推导、React 19 并发安全、性能优化。
  • 企业级细节:清除、前后缀、字数统计、防抖、校验、样式隔离、无障碍。

知识点

  1. 受控判定黄金法则:value !== undefined 即为受控,否则为非受控。
  2. 内部状态仅作为“兜底”,一旦检测到 value 从 undefined 变为非 undefined,须立即丢弃内部状态,防止 value 与 defaultValue 打架。
  3. 使用 useImperativeHandle 暴露 focus/blur/scrollIntoView 等命令式方法,满足表单库(如 antd/formik)的 ref 需求。
  4. TypeScript 泛型约束:当 value 存在时,onChange 必传;当 value 不存在时,onChange 可选。利用“条件类型”让编译器自动推导。
  5. React 19 Concurrent Features:在 startTransition 内更新内部状态,避免输入卡顿;同步 flush 受控回调,保障表单校验实时性。
  6. 性能:用 React.memo + 自定义 areEqual 跳过父级无关重渲染;输入阶段用 requestAnimationFrame 节流,兼顾中文输入法。
  7. 安全:禁止在 componentDidMount 阶段直接操作真实 DOM,避免与服务端渲染结果不一致(hydration mismatch)。

答案

import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
  useTransition,
  ChangeEvent,
  InputHTMLAttributes,
} from 'react';

type ControlledProps<T> = {
  value: T;
  onChange: (val: T) => void;
  defaultValue?: never;
};

type UncontrolledProps<T> = {
  value?: never;
  onChange?: (val: T) => void;
  defaultValue?: T;
};

export type InputRef = {
  focus: () => void;
  blur: () => void;
  getValue: () => string;
};

type BaseProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'value' | 'defaultValue' | 'onChange'> & {
  debounce?: number; // 毫秒
  maxLength?: number;
};

function isControlled<T>(props: ControlledProps<T> | UncontrolledProps<T>): props is ControlledProps<T> {
  return props.value !== undefined;
}

function InternalInput<T extends string = string>(
  props: BaseProps & (ControlledProps<T> | UncontrolledProps<T>),
  ref: React.Ref<InputRef>
) {
  const { debounce = 0, maxLength, ...rest } = props;
  const inputRef = useRef<HTMLInputElement>(null);
  const [innerValue, setInnerValue] = useState(() =>
    isControlled(props) ? props.value : props.defaultValue ?? ('' as T)
  );
  const [, startTransition] = useTransition();
  const timerRef = useRef<number | null>(null);

  // 受控优先级:一旦外部传入 value,内部状态立即失效
  useEffect(() => {
    if (isControlled(props) && innerValue !== props.value) {
      setInnerValue(props.value);
    }
  }, [props.value]);

  const realValue = isControlled(props) ? props.value : innerValue;

  const flush = (next: T) => {
    if (isControlled(props)) {
      props.onChange(next);
    } else {
      startTransition(() => setInnerValue(next));
      props.onChange?.(next);
    }
  };

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    let next = e.target.value as T;
    if (maxLength !== undefined) next = next.slice(0, maxLength) as T;

    if (debounce <= 0) {
      flush(next);
      return;
    }

    if (timerRef.current) window.clearTimeout(timerRef.current);
    timerRef.current = window.setTimeout(() => flush(next), debounce);
  };

  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current?.focus(),
    blur: () => inputRef.current?.blur(),
    getValue: () => realValue,
  }));

  return (
    <input
      {...rest}
      ref={inputRef}
      value={realValue}
      onChange={handleChange}
    />
  );
}

export const SmartInput = React.memo(forwardRef(InternalInput)) as <T extends string = string>(
  props: BaseProps & (ControlledProps<T> | UncontrolledProps<T>) & { ref?: React.Ref<InputRef> }
) => JSX.Element;

使用示例:

// 受控
const [v, setV] = useState('');
<SmartInput value={v} onChange={setV} debounce={300} />;

// 非受控
const ref = useRef<InputRef>(null);
<SmartInput defaultValue="hello" onChange={console.log} ref={ref} />;

拓展思考

  1. 表单级联动:若把 SmartInput 放入 React Hook Form,只需注册 ref 即可,无需额外 Controller 包装,性能最佳。
  2. 服务端渲染:在 Next.js App Router 中,确保 defaultValue 与服务器生成的 HTML 一致,避免 hydration error;若必须异步获取默认值,可在客户端挂载后再渲染输入框。
  3. 复合组件:把 SmartInput 拓展为 Password、Search、Textarea 等子组件,共用同一套受控/非受控逻辑,通过 as 属性做 polymorphic 渲染,减少重复代码。
  4. 安全加固:在 handleChange 里对敏感字段(手机号、身份证)做脱敏正则,防止开发者把明文打印到日志。
  5. 微前端场景:若被无界、qiankan 等微前端框架嵌入,需把 window.setTimeout 换成 import { setTimeout } from 'timers' 的隔离版本,防止主子应用计时器冲突。