react如何引用传递
引用传递的概念
在React中,引用传递(Ref Forwarding)是一种将ref属性自动传递给子组件的技术。这对于高阶组件(HOC)或封装第三方组件时非常有用,允许父组件直接访问子组件的DOM节点或组件实例。
基本用法
使用React.forwardRef函数可以创建一个接收ref参数的组件。以下是一个简单的示例:
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="fancy-button">
{props.children}
</button>
));
// 父组件中使用
const ParentComponent = () => {
const buttonRef = React.useRef();
return <FancyButton ref={buttonRef}>Click me</FancyButton>;
};
高阶组件中的引用传递
在高阶组件中,引用传递可以确保ref不会被HOC拦截,而是直接传递给被包装的组件:
function withLogging(WrappedComponent) {
return React.forwardRef((props, ref) => {
return <WrappedComponent {...props} ref={ref} />;
});
}
const EnhancedComponent = withLogging(FancyButton);
类组件中的引用传递
对于类组件,可以通过React.forwardRef包装后传递ref:
class MyComponent extends React.Component {
render() {
return <div ref={this.props.innerRef}>Content</div>;
}
}
const ForwardedMyComponent = React.forwardRef((props, ref) => (
<MyComponent {...props} innerRef={ref} />
));
注意事项
- 引用传递仅适用于函数组件或
forwardRef包装的组件,类组件需要通过props手动传递ref。 - 避免滥用引用传递,优先考虑通过
props控制子组件的行为。 - 在TypeScript中,需要明确声明
forwardRef的泛型类型以确保类型安全。







