CSS transition , react-transition-group and React.findDOMnod



当尝试使用react routing时,我遇到了一个相对于findDOMnode弃用的警告与react-transition-group结合使用,警告如下:

index.js:1警告:在StrictMode中已弃用findDOMNode。findDOMNode传递了一个Transition的实例,它位于StrictMode内部。相反,直接向要引用的元素添加一个ref。在这里了解更多关于安全使用refs的信息:https://reactjs.org/link/strict-mode-find-node

上述警告指的是以下代码:

<Route  key={path} path={path} exact>

{({match})=>(
<CSSTransition

in={match!=null}
timeout={300}
classNames="page"
unmountOnExit
mountOnEnter

>
<div  className="page">

<Component />
</div>
</CSSTransition>  
)}
</Route>)  

我第一次尝试摆脱这个警告是使用useRef的建议:

const nodeRef = useRef(null);

传递nodeRef作为CSStransation元素的ref prop,但警告仍然显示。

由于某种原因,我只能通过传递触发事件来摆脱警告,我也在cstransition元素的'in' prop中使用了触发事件,如下所示:

<Route  key={path} path={path} exact>

{({match})=>(
<CSSTransition

ref={nodeRef}
in={match!=null}
timeout={300}
classNames="page"
unmountOnExit
mountOnEnter
key={match!=null}    <------------ Adding this removed the warning
>
<div  className="page">

<Component />
</div>
</CSSTransition>  
)}
</Route>) 

现在一切工作顺利,但我真的不明白为什么,即使我从cstransform元素中删除ref,我也不会得到任何警告了。

有人明白为什么会发生这种情况吗?

我花了一段时间试图弄清楚这个,我终于得到了它!您需要为每条路由单独使用CSSTransition中的nodeRefprop。每条路由都有自己的ref,并且ref需要相应地分配给nodeRef。我能够通过使用refs数组,映射每个路由并将refs分配给当前索引来实现此工作。

看一下我做的这个工作示例:

  • https://codesandbox.io/s/react-transition-routes-with-noderef-k9q47

下面这段代码将是最有用的:

////// CONTENT TRANSITION ROUTER
const PageContent = withRouter(({ location }) => {
let routeRefs: any[] = [];
const isMatch = useCallback(
(path: string): boolean => {
return location.pathname === path ? true : false;
},
[location]
);
return (
<>
{appRoutes.map(({ path, Component }, index) => {
routeRefs[index] = React.useRef(null);
return (
<Route key={index} exact path={path}>
{() => {
// Route callback ensures the transitions are loaded correctly
return (
<CSSTransition
nodeRef={routeRefs[index]}
in={isMatch(path)}
timeout={300}
classNames="fade"
unmountOnExit
appear
>
<div ref={routeRefs[index]} className="fade">
<Component />
</div>
</CSSTransition>
);
}}
</Route>
);
})}
</>
);
});

最新更新