3

我只是尝试将 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 中的组件一起使用?

4

1 回答 1

4

在高阶组件中转发 refs

... refs 不会通过。那是因为ref不是道具。就像key,React 对它的处理方式不同。如果向 HOC 添加 ref,则 ref 将引用最外层的容器组件,而不是包装的组件。

看起来withRouterHOC 还没有转发 refs。您可以创建自己的小 HOC 来将 ref 转发到 decorated-with-router 组件

const withRouterForwardRef = Component => {
  const WithRouter = withRouter(({ forwardedRef, ...props }) => (
    <Component ref={forwardedRef} {...props} />
  ));

  return forwardRef((props, ref) => (
    <WithRouter {...props} forwardedRef={ref} />
  ));
};

用法:

const ChildWithRoute = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    say: () => console.log("hello from child with route"),
  }));

  return <div>ChildWithRoute</div>;
})

const ChildWithRouteAndRef = withRouterForwardRef(ChildWithRoute);

...
<ChildWithRouteAndRef ref={childWithRouteRef} />

编辑 forwardRef - HOC

经过快速的谷歌搜索后,我发现了这个问题,并且根据时间戳和最后的评论似乎不太可能得到解决。我的上述解决方案类似于共享的几种方法。

于 2020-05-12T05:48:34.770 回答