react-transition-group新版本使用中经常会出现这个warning

来源:7-9 拿来主义 - 自定义 Transition 组件编码第二部分

weixin_慕先生2095971

2020-11-11

waning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of Transition which is inside StrictMode. Instead, add a ref directly to the element you want to reference.
我看了一下对应的issue:https://github.com/reactjs/react-transition-group/issues/668
然后将Transition中的组件代码按照里面的解决方案,在CSSTransition中添加上了一个nodeRef,如下所示,

const Transition: React.FC<TransitionProps> = (props) => {
  const { children, classNames, animation, wrapper, ...restProps } = props;
  const nodeRef = React.useRef(null);
  return (
    <CSSTransition
      nodeRef={nodeRef}
      classNames={classNames ? classNames : animation}
      {...restProps}
    >
      {wrapper ? <div ref={nodeRef}>{children}</div> : children}
    </CSSTransition>
  );
};

这样子一试,这个警告就消失了,但是也出现了一个问题,就是如果不使用wrapper,根本不会起到动画效果。
但是给每个使用Transition的地方都去添加一个wrapper会不合适,比如在submenu中。因为添加了wrapper,多了一层div会出现下拉框抖动,所以我只能改成用下面代码。

const Transition: React.FC<TransitionProps> = (props) => {
  const { children, classNames, animation, wrapper, ...restProps } = props;
  const nodeRef = React.useRef(null);
  return wrapper ? (
    <CSSTransition
      nodeRef={nodeRef}
      classNames={classNames ? classNames : animation}
      {...restProps}
    >
      {<div ref={nodeRef}>{children}</div>}
    </CSSTransition>
  ) : (
    <CSSTransition
      classNames={classNames ? classNames : animation}
      {...restProps}
    >
      {children}
    </CSSTransition>
  );

这样子在使用wrapper时没问题,但如何取消使用wrapper时的报警呢?

写回答

1回答

张轩

2020-11-12

同学你好  你能自己发现问题和寻找解决方法 非常好

由于这个错误是 CSSTransition组件 内部的警告,所以在这里我们只能看这个 issue,目前只能是添加 ref 这种方法。你的第二种方法还是会出现警告,所以结果就是必须添加外层的 div。把 wrapper 这个参数删除掉,然后想办法用样式修复多一层 div 出现的问题。


0
2
Duweber
回复
weixin_慕先生2095971
为什么会跳一下,我也遇到了,没找到原因
2022-04-09
共2条回复

React18+TS高仿AntD从零到一打造组件库

设计,开发,测试,发布再到 CI/CD,从0到1造轮子

2124 学习 · 959 问题

查看课程