HOC里怎么正确传递ref到被包装的组件?
我在用高阶组件(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包裹?具体该怎么改?
这样ref就能正确拿到原始组件的实例了。