带有样式组件的动画,如何简化代码

问题描述

我有一个动画显示鼠标悬停时的前缀 demo

const Div = styled.div<{ width: number }>`
  transition: opacity 0.25s 0.25s ease,width 0.25s ease;
  width: ${(props) => props.width + "px"};
  &.enter {
    transition: opacity 0.25s 0.25s ease,width 0.25s ease;
    width: 0;
    opacity: 0;
  }
  &.enter-active {
    width: ${(props) => props.width + "px"};
    opacity: 1;
  }
  &.exit {
    transition: opacity 0.25s ease,width 0.25s 0.25s ease;
    width: ${(props) => props.width + "px"};
    opacity: 1;
  }
  &.exit-active {
    width: 0;
    opacity: 0;
  }
`;

export const Animation = (props: { visible: boolean; children: any }) => {
  const [width,setWidth] = useState(0);

  const ref = useRef<any>(null);

  useEffect(() => {
    if (ref.current) {
      setWidth(+ref.current.scrollWidth);
    }
  },[ref,props.visible]);

  return (
    <Csstransition
      in={props.visible}
      classNames=""
      timeout={500}
      nodeRef={ref}
      mountOnEnter
      unmountOnExit
    >
      <Div ref={ref} width={width}>
        {props.children}
      </Div>
    </Csstransition>
  );
};

我不明白为什么需要 CSS 的第一部分:

transition: opacity 0.25s 0.25s ease,width 0.25s ease;
width: ${(props) => props.width + "px"};

似乎 .enter-active 类应用不正确。

我还想知道我是否可以在没有 react-transition-group 的情况下实现所有这些?

注意:我必须使用 mountOnEnter unmountOnExit

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)