react如何引用传递
引用传递的概念
在 React 中,引用传递(Ref Forwarding)是一种将 ref 属性自动传递给子组件的技术。默认情况下,ref 不会像普通 props 那样传递,需要通过 forwardRef 显式实现。

基本用法
使用 React.forwardRef 包装子组件,将 ref 作为第二个参数传递:

const ChildComponent = React.forwardRef((props, ref) => {
return <div ref={ref}>{props.children}</div>;
});
// 父组件中使用
function ParentComponent() {
const childRef = React.useRef();
return <ChildComponent ref={childRef}>Content</ChildComponent>;
}
类组件中的引用传递
类组件需要通过 forwardRef 包裹,并在子组件内部将 ref 绑定到 DOM 元素或实例:
class ChildClass extends React.Component {
render() {
return <div ref={this.props.ref}>Class Component</div>;
}
}
const ForwardedChild = React.forwardRef((props, ref) => (
<ChildClass ref={ref} {...props} />
));
高阶组件(HOC)中的引用传递
若子组件被高阶组件包装,需通过 forwardRef 确保 ref 穿透到原始组件:
function withLogging(WrappedComponent) {
return React.forwardRef((props, ref) => {
return <WrappedComponent ref={ref} {...props} />;
});
}
注意事项
ref仅能用于 DOM 元素或类组件实例,函数组件默认无实例。- 避免滥用
ref,优先通过props和状态管理数据流。 - 使用
useImperativeHandle可自定义暴露给父组件的实例方法(函数组件中)。
示例:函数组件暴露方法
const Child = React.forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus()
}));
return <input ref={inputRef} />;
});






