React / 知识点

React Hooks 速查手册

手册条目

使用 useImperativeHandle 限制父组件通过 ref 可调用的命令。

使用 useImperativeHandle 暴露命令接口

当父组件确实需要执行聚焦、滚动、播放动画或清空输入等命令式操作时,用 useImperativeHandle 只暴露允许调用的方法,避免父组件直接获得完整 DOM 节点或修改子组件内部状态。其基本签名是 useImperativeHandle(ref, createHandle, dependencies?)。:contentReference[oaicite:0]{index=0}

基本语法

tsx
useImperativeHandle(ref, () => ({
  focus() {
    // 执行子组件内部操作
  },
}), []);

createHandle 返回父组件最终从 ref.current 读取的对象。依赖数组中应列出该对象使用的响应式变量;遗漏依赖可能让命令读取旧的 props 或 state。

主示例

下面的输入框只向父组件开放 focus 和 clear,不暴露底层 <input>:

tsx
import {
  forwardRef,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';

type InputCommands = {
  focus: () => void;
  clear: () => void;
};

type CommandInputProps = {
  initialValue?: string;
};

const CommandInput = forwardRef<InputCommands, CommandInputProps>(
  function CommandInput({ initialValue = 'demo' }, ref) {
    const inputRef = useRef<HTMLInputElement>(null);
    const [value, setValue] = useState(initialValue);

    useImperativeHandle(
      ref,
      () => ({
        focus() {
          inputRef.current?.focus();
        },
        clear() {
          setValue('');
          inputRef.current?.focus();
        },
      }),
      [],
    );

    return (
      <input
        ref={inputRef}
        value={value}
        onChange={(event) => setValue(event.target.value)}
      />
    );
  },
);

export default function App() {
  const inputCommands = useRef<InputCommands>(null);

  return (
    <main>
      <CommandInput ref={inputCommands} />
      <button onClick={() => inputCommands.current?.focus()}>
        聚焦
      </button>
      <button onClick={() => inputCommands.current?.clear()}>
        清空并聚焦
      </button>
    </main>
  );
}

预期结果:

text
页面初始显示值 demo。
点击“聚焦”后,光标进入输入框。
点击“清空并聚焦”后,内容被清空且输入框保持焦点。
父组件只能调用 focus() 和 clear()。

高频用法

  • 表单组件暴露 focus()、reset() 或 validate()。
  • 播放器组件暴露 play()、pause() 和 seek()。
  • 虚拟列表暴露 scrollToItem(index)。
  • 动画组件暴露 start() 或 cancel()。

优先暴露业务含义明确的命令,例如 scrollToError(),不要把内部 DOM 节点直接返回给父组件。

风险与边界

当界面状态能由 props 表达时,应优先使用声明式数据流。例如弹窗开关通常使用 open 属性,而不是暴露 open() 和 close()。滥用命令接口会增加父子组件耦合,使状态来源难以追踪。React 官方也建议仅将 ref 用于无法通过 props 清晰表达的命令式行为。:contentReference[oaicite:1]{index=1}

若命令引用会变化的 props、state 或函数,却把依赖数组写成 [],父组件可能调用到旧逻辑。安全做法是补齐依赖,或使用函数式状态更新和稳定回调减少闭包依赖。

排障清单

  • ref.current 为 null:确认组件已经挂载,并且 ref 确实传给目标组件。
  • 提示方法不存在:检查 useImperativeHandle 返回对象的方法名是否与父组件类型一致。
  • 命令读取旧数据:检查依赖数组是否遗漏 props、state 或组件内函数。
  • TypeScript 推断为 never 或 null:给 useRef<InputCommands>(null) 和 forwardRef 补充泛型。
  • 父组件能任意修改样式:检查是否错误地暴露了 inputRef.current 等完整 DOM 节点。

兼容性

React 19 可将 ref 作为组件属性直接接收;React 18 及更早版本需要通过 forwardRef 接收。上面的写法可兼容 React 18,并能继续用于 React 19 项目。:contentReference[oaicite:2]{index=2}

目录与阅读设置

记录一个想法

React Hooks 速查手册

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通