HOC里怎么正确传递ref到被包装的组件?

♫东芳 阅读 4

我在用高阶组件(HOC)封装一个通用逻辑,但发现ref拿不到原始组件的实例,试了直接传ref进去好像不行,是不是得用React.forwardRef?

比如我现在的HOC是这样写的:

function withLoading(WrappedComponent) {
  return function WithLoading(props) {
    const [loading, setLoading] = useState(false);
    return ;
  };
}

// 使用时
const MyButtonWithRef = withLoading(MyButton);
const ref = useRef();
// 这里ref.current 是 null 或 undefined
<MyButtonWithRef ref={ref} />

是不是必须在HOC里用forwardRef包裹?具体该怎么改?

我来解答 赞 0 收藏
二维码
手机扫码查看
1 条解答
打工人甜茜
对,HOC里必须用React.forwardRef把ref透传下去才行。

function withLoading(WrappedComponent) {
return React.forwardRef((props, ref) => {
const [loading, setLoading] = useState(false);
return ;
});
}


这样ref就能正确拿到原始组件的实例了。
点赞
2026-03-13 16:33