react元素创建删除动画怎么写比较好?

作者站长头像
站长
· 阅读数 20

css

.ani-fadeIn{animation: fadeIn .5s ease-in-out both;}

@keyframes fadeIn {0%{opacity: 0;}100%{opacity: 1;}}

.ani-fadeOut{animation: fadeOut .5s linear both;}

@keyframes fadeOut {0%{opacity: 1;}100%{opacity: 0;}}

组件

function Example(){

  const [nextStep,setNextStep] = useState(false)

  const [aniType,setAniType] = useState(false)

  return(
    <>
        <button onClick={()=>setNextStep(true)}>显示</button>
        {
          nextStep &&
            <>
              <button onClick={() => setAniType(true)}>隐藏</button>
              <div
                className={aniType ? 'ani-fadeOut': 'ani-fadeIn'}
                onAnimationEnd={(e) => {
                  if (e.animationName == "fadeOut") {
                    setNextStep(false);
                    setAniType(false);
                  }
                }}
              >123</div>
            </>
        }
    </>
  )
}

如上代码是我写的效果,有没有更好的写法(可以的话,最好不要用库,例如react-transition-group)

回复
1个回答
avatar
test
2024-07-04

不想用库的话,你可以自定义Hook来管理动画类名:

import React, { useState, useCallback } from 'react';
import './App.css';

// 自定义 Hook,用于管理动画
function useAnimation(animationClassNames) {
  const [animationClassName, setAnimationClassName] = useState('');

  const triggerAnimation = useCallback((animationName, onEnd) => {
    setAnimationClassName(animationClassNames[animationName]);
    const onAnimationEnd = (e) => {
      if (e.animationName === animationName) {
        setAnimationClassName('');
        onEnd?.();
      }
    };
    return onAnimationEnd;
  }, [animationClassNames]);

  return [animationClassName, triggerAnimation];
}

function Example() {
  const [isVisible, setIsVisible] = useState(false);
  const [animationClassName, triggerAnimation] = useAnimation({
    fadeIn: 'ani-fadeIn',
    fadeOut: 'ani-fadeOut',
  });

  const handleShow = () => {
    setIsVisible(true);
  };

  const handleHide = () => {
    triggerAnimation('fadeOut', () => {
      setIsVisible(false);
    });
  };

  return (
    <>
      <button onClick={handleShow}>显示</button>
      {isVisible && (
        <>
          <button onClick={handleHide}>隐藏</button>
          <div className={animationClassName}>123</div>
        </>
      )}
    </>
  );
}

export default Example;
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容