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

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)

阅读 3.4k
2 个回答

不想用库的话,你可以自定义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;

你可以用用animate.js这类库来实现动画控制

Animate.js

用起来就像

cosnt animeInstance = anime({
    targets: targetRef.current,
    translateX: 250,
    easing: 'linear',
    duration: 5000
})
if ( something ){
    animeInstance.pause()
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题