我只是尝试将 forwardRef 与 withRouter(mycomponent) 一起使用,如下所示:
export default function App() {
const childRef = useRef();
const childWithRouteRef = useRef();
useEffect(()=>{
console.log("childWithRouteRef",childWithRouteRef);
childRef.current.say();
childWithRouteRef.current.say();
})
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<BrowserRouter>
<Child ref={childRef}/>
<ChildWithRoute_ ref={childWithRouteRef}/>
</BrowserRouter>
</div>
);
}
const Child = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
say: () => {
console.log("hello")
},
}));
return <div>Child</div>
})
const ChildWithRoute = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
say: () => {
console.log("hello")
},
}));
return <div>ChildWithRoute</div>
})
const ChildWithRoute_ = withRouter(ChildWithRoute)
如果我将组件包装在 withRouter HOC 中,则 ref 将不起作用,它始终为空。那么如何将 forwardRef 与包装在 withRouter 中的组件一起使用?