目标:非常简单,给定一个状态
showStupid
,我想在<StupidComponent />
时安装/显示showStupid===true
。
另外,如果可能的话,我更愿意使用
useAnimate
。我根据他们网站的示例尝试了以下操作:https://www.framer.com/motion/use-animate/##exit-animations
// StupidComponent.tsx
import React, { useEffect } from 'react'
import { useAnimate } from 'framer-motion'
export function StupidComponent() {
const [scope, animate] = useAnimate() // Define the animation scope
useEffect(() => {
// When the component is mounted, animate to the final state
animate(
scope.current,
{
scale: 1,
},
{
duration: 0.5, // Animation duration
ease: 'easeInOut', // Animation easing
}
)
return () => {
// When unmounting, no animation needed
// Set the default scale explicitly without triggering animation
if (scope.current) {
scope.current.style.transform = 'scale(0.5)' // Default scale
}
}
}, [animate, scope])
return (
<div ref={scope} className="p-4 bg-orange-400 text-white">
This component scales to 1 when it appears.
</div>
)
}
// App.tsx
import { useState } from 'react'
import { StupidComponent } from '@/components/StupidComponent'
export const App = () => {
const [showStupid, setShowStupid] = useState(false)
return (
<>
<Button
onClick={() => {
setShowStupid((prev) => !prev)
}}
>
Show stupid
</Button>
{showStupid && <StupidComponent />}
</>
)
}
目前,当我单击按钮时,组件显示时没有动画
所以你可以做一些CSS东西来为秤入口设置动画。但如果您想将其全部保留在框架运动中,文档中有一些有关动画入口的信息。您可能可以在没有 useAnimate 挂钩的情况下完成此操作,但如果您想保留它,则应该将
div
设置为 StupidComponent 内部的 motion.div
。然后你可以在动画运行之前给它一个初始值。
function StupidComponent() {
const [scope, animate] = useAnimate() // Define the animation scope
useEffect(() => {
// When the component is mounted, animate to the final state
animate(
scope.current,
{
scale: 1,
},
{
duration: 0.5, // Animation duration
ease: 'easeInOut', // Animation easing
}
)
}, [animate, scope])
return (
<motion.div initial={{scale: 0.5}} ref={scope} className="p-4 bg-orange-400 text-white">
This component scales to 1 when it appears.
</motion.div>
)
}
但是,您可以删除 useAnimate 并将其进一步简化为类似这样的内容,我们在 div 中设置所需的动画。
function StupidComponent() {
return (
<motion.div initial={{scale: 0.5}} animate={{scale: 1}} className="p-4 bg-orange-400 text-white">
This component scales to 1 when it appears.
</motion.div>
)