react如何引用传递
在React中引用传递(Ref Forwarding)是一种将ref自动通过组件传递到子组件的技术,通常用于访问子组件的DOM节点或实例。以下是具体实现方法:
使用React.forwardRef
React.forwardRef允许组件接收ref并将其向下传递给子组件。适用于函数组件或需要直接操作DOM的场景。
const ChildComponent = React.forwardRef((props, ref) => {
return <input ref={ref} {...props} />;
});
function ParentComponent() {
const inputRef = React.useRef(null);
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<ChildComponent ref={inputRef} />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
类组件中的ref传递
类组件可以通过ref属性直接传递,但需注意命名冲突。
class ChildComponent extends React.Component {
render() {
return <input ref={this.props.innerRef} />;
}
}
const ForwardedChild = React.forwardRef((props, ref) => (
<ChildComponent {...props} innerRef={ref} />
));
function ParentComponent() {
const inputRef = React.useRef(null);
// 使用方式与函数组件相同
}
高阶组件(HOC)中的ref转发
若组件经过高阶组件包装,需通过forwardRef确保ref不被丢失。
function withLogging(WrappedComponent) {
return React.forwardRef((props, ref) => {
console.log('Props:', props);
return <WrappedComponent {...props} ref={ref} />;
});
}
const EnhancedComponent = withLogging(ChildComponent);
动态组件中的ref
动态组件(如通过React.lazy加载)需结合forwardRef使用:
const LazyComponent = React.lazy(() => import('./ChildComponent'));
const ForwardedLazy = React.forwardRef((props, ref) => (
<LazyComponent {...props} ref={ref} />
));
注意事项
- 命名冲突:避免将
ref作为普通prop传递,需使用forwardRef的机制。 - 性能优化:频繁更新的ref可能导致不必要的渲染,可结合
useCallback或useMemo优化。 - TypeScript支持:为转发ref的组件添加类型注解:
const ChildComponent = React.forwardRef<HTMLInputElement>((props, ref) => ( <input ref={ref} {...props} /> ));
通过上述方法,可以灵活地在React组件树中传递和操作ref。







