传递给自定义组件的 ref 不会自动到达其内部的 DOM 节点。forwardRef 让组件接收 ref 并将其附加到子元素。useImperativeHandle 自定义该 ref 暴露的内容。
为什么这很重要
jsx
= ( () {
;
});
ref = ();
;
有时您不想泄露整个 DOM 节点——只是特定的方法:
const FancyInput = forwardRef(function FancyInput(props, ref) {
const inner = useRef(null);
useImperativeHandle(ref, () => ({
focus: () => inner.current.focus(),
clear: () => { inner.current.value = ""; },
}), []);
return <input ref={inner} {...props} />;
});
// parent: fancyRef.current.focus(); fancyRef.current.clear();
优先使用 props/state 进行通信。仅在真正必要的需求下使用 ref:焦点管理、滚动、文本选择、媒体播放或集成命令式库。注意:在 React 19 中,ref 可以作为普通 prop 传递,因此通常不再需要 forwardRef。