React - animate mount and unmount of a single component

前端 未结 16 1659
南笙
南笙 2020-12-22 16:34

Something this simple should be easily accomplished, yet I\'m pulling my hair out over how complicated it is.

All I want to do is animate the mounting & unmounti

16条回答
  •  感情败类
    2020-12-22 17:01

    I know there are a lot of answers here, but I still did not find one that suits my needs. I want:

    • Functional components
    • A solution that'll allow my components to easily fade in/out when they're mounted/unmounted.

    After many hours of fiddling, I have a solution that works I'd say 90%. I've written the limitation in a comment block in the code below. I'd still love a better solution, but this is the best I've found, including the other solutions here.

    const TIMEOUT_DURATION = 80 // Just looked like best balance of silky smooth and stop delaying me.
    
    // Wrap this around any views and they'll fade in and out when mounting /
    // unmounting.  I tried using  and  but I
    // could not get them to work.  There is one major limitation to this approach:
    // If a component that's mounted inside of  has direct prop changes,
    //  will think that it's a new component and unmount/mount it.  This
    // means the inner component will fade out and fade in, and things like cursor
    // position in forms will be reset. The solution to this is to abstract 
    // into a wrapper component.
    
    const Fade: React.FC<{}> = ({ children }) => {
      const [ className, setClassName ] = useState('fade')
      const [ newChildren, setNewChildren ] = useState(children)
    
      const effectDependency = Array.isArray(children) ? children : [children]
    
      useEffect(() => {
        setClassName('fade')
    
        const timerId = setTimeout(() => {
          setClassName('fade show')
          setNewChildren(children)
        }, TIMEOUT_DURATION)
    
        return () => {
          clearTimeout(timerId)
        }   
    
      }, effectDependency)
    
      return {newChildren}
    }
    

    If you have a component you want to fade in/out, wrap it in Ex. .

    Note that this uses react-bootstrap for the class names and for , but both could be easily replaced with custom CSS and a regular old

    .

提交回复
热议问题