Kaz*_*Ute 4 animation css-animations reactjs framer-motion
根据文档,我可以使变体属性动态化:https://www.framer.com/docs/animation/##dynamic-variants。
但当我尝试使属性动态化时,这不起作用initial。
例如:
import React, { useState, useEffect } from "react";
import { motion, useAnimation } from "framer-motion";
//make div appear from either bottom or right, depending on "origin" custom prop
const variant = {
hidden: (origin) =>
origin === "bottom"
? { x: 0, y: 200, opacity: 0 }
: { x: 200, y: 0, opacity: 0 },
visible: { x: 0, y: 0, opacity: 1, transition: { duration: 1 } },
};
function App() {
const [origin, setOrigin] = useState("bottom");
const controls = useAnimation();
//after 2 secs make origin "right"
useEffect(() => {
setTimeout(() => {
setOrigin("right");
}, 2000);
}, []);
//after 4 secs start the animation
useEffect(() => {
setTimeout(() => {
controls.start("visible");
}, 4000);
}, [controls]);
return (
<motion.div
style={{ width: 100, height: 50, background: "red" }}
variants={variant}
initial="hidden"
animate={controls}
custom={origin}
/>
);
}
export default App;
Run Code Online (Sandbox Code Playgroud)
在这里,我做了一个动态变体,使 div 从右侧或底部出现,我可以通过 prop 进行控制custom。最初该custom道具设置为“底部”。2 秒后,变为“右”。当我在 4 秒后开始动画时,我希望 div 从右侧出现,但它仍然从底部出现:
这是因为该组件已经渲染,并且即使origin传递给组件的 prop 已更改,它仍然是同一组件。
你可以做两件事:
isVisible状态变量,该render方法将观察更改并在状态变为 时渲染组件true。function App() {
const [isVisible, setIsVisible] = useState(false);
...
//after 4 secs start the animation
useEffect(() => {
setTimeout(() => {
setIsVisible(true);
controls.start("visible");
}, 4000);
}, [controls]);
return (
isVisible && (
<motion.div
...
/>
)
);
}
Run Code Online (Sandbox Code Playgroud)
keyprop,以便当该值发生变化时,React 将重新渲染该组件。function App() {
...
return (
<motion.div
key={origin}
...
/>
);
}
Run Code Online (Sandbox Code Playgroud)
如果您需要在origin.
| 归档时间: |
|
| 查看次数: |
4437 次 |
| 最近记录: |