发布于 2026-01-06 0 阅读
0

styled-component + react-transition-group = 非常简单的过渡示例预览淡入淡出示例

styled-component + react-transition-group = 非常简单的过渡效果

例子

预览

淡入淡出示例

如果我们需要为 React 组件添加动画效果,可以使用像react-posereact-spring 这样的库。这些库功能强大,但如果只需要简单的过渡效果,它们就显得过于臃肿了。

另一方面,react-transition-group非常简单。

如果我们使用styled-componets<Transition>组件可能比<CSSTransition>

例子

首先,我创建了一个带有过渡效果的组件。
在这个例子中,我使用了 React Hooks,但你也可以根据需要使用类组件。



import { Transition } from "react-transition-group"
import { Animation } from "./Animation"

export const AnimateItem = () => {
  const [animate, setAnimate] = useState(false)

  // Animate on click button and revert after 3000ms.
  const doAnimate = useCallback(() => {
    setAnimate(true)
    setTimeout(() => {
      setAnimate(false)
    }, 3000)
  }, [])

  return (
    <div>
      {/* Transition change state with `in` props */}
      <Transition in={animate} timeout={500}>
        {(state) => (
          // state change: exited -> entering -> entered -> exiting -> exited
          <Animation state={state}>Hello</Animation>
        )}
      </Transition>
      <button onClick={doAnimate}>Animate</button>
    </div>
  )
}


Enter fullscreen mode Exit fullscreen mode

接下来,创建一个基于 styled-component 的组件。



// Animation.js
import styled from "styled-components"

export const Animation = styled.div`
  transition: 0.5s;
  width: 300px;
  height: 200px;
  /* example for move item */
  transform: translateX(
    ${({ state }) => (state === "entering" || state === "entered" ? 400 : 0)}px
  );
  /* change color*/
  background: ${({ state }) => {
    switch (state) {
      case "entering":
        return "red"
      case "entered":
        return "blue"
      case "exiting":
        return "green"
      case "exited":
        return "yellow"
    }
  }};
`


Enter fullscreen mode Exit fullscreen mode

Item你也可以拆分Animation



const BaseItem = styled.div`
  width: 300px;
  height: 200px;
`

export const Animation = styled(BaseItem)`
  transition: 0.5s;
  transform: translateX(
    ${({ state }) => (state === "entering" || state === "entered" ? 400 : 0)}px
  );
`


Enter fullscreen mode Exit fullscreen mode

预览

预览

淡入淡出示例

您也可以用同样的方法创建淡入/淡出动画。



export const Fade = styled.div`
  transition: 0.5s;
  opacity: ${({ state }) => (state === "entered" ? 1 : 0)};
  display: ${({ state }) => (state === "exited" ? "none" : "block")};
`


Enter fullscreen mode Exit fullscreen mode

或者你可以使用 withunmountOnExitmountOnEnter




export const Fade2 = styled.div`
  transition: 5s;
  opacity: ${({ state }) => (state === "entered" ? 1 : 0)};
`

const Item = () => {
  // ...
  return <Transition in={animate} timeout={500} unmountOnExit mountOnEnter>
    {(state) => <Fade2 state={state}>Fade In</Fade2>}
  </Transition>
}



Enter fullscreen mode Exit fullscreen mode
文章来源:https://dev.to/terrierscript/styled-component--react-transition-group--very-simple-transition-jja