【问题标题】:what is the right way to use forwardRef with withRouter将 forwardRef 与 withRouter 一起使用的正确方法是什么
【发布时间】:2020-08-27 19:25:45
【问题描述】:

我只是尝试将 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 将不起作用,它始终为 null。那么如何将 forwardRef 与包装在 withRouter 中的组件一起使用?

【问题讨论】:

    标签: reactjs react-router react-forwardref react-hoc


    【解决方案1】:

    Forwarding refs in higher order components

    ... refs 不会被通过 通过。那是因为ref 不是道具。像key一样处理 与 React 不同。如果您将 ref 添加到 HOC,则 ref 将引用 最外层的容器组件,而不是被包裹的组件。

    看起来withRouter HOC 还没有转发 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} />
    

    在谷歌快速搜索后,我找到了这个issue,根据时间戳和最后一条评论似乎不太可能得到解决。我上面的解决方案类似于共享的几种方法。

    【讨论】:

      猜你喜欢
      • 2021-09-10
      • 2018-04-10
      • 2013-01-02
      • 1970-01-01
      • 2020-07-10
      • 2020-09-29
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      相关资源
      最近更新 更多