我正在尝试使用每次用户在图像旋转木马中单击下一步时加载页面时使用的动画。
我尝试使用与此类似的react-springs:
const springs = useSprings(cards.map(item => ({ opacity: item.opacity }))
但是我得到了" typeError:无法读取未定义的属性'0'
使用使用(非载体(时,这是在工作:
import React, { useState } from "react";
import { useSpring, animated } from "react-spring";
import "./App.css";
const cards = [
"https://upload.wikimedia.org/wikipedia/en/f/f5/RWS_Tarot_08_Strength.jpg",
"https://upload.wikimedia.org/wikipedia/en/5/53/RWS_Tarot_16_Tower.jpg",
"https://upload.wikimedia.org/wikipedia/en/9/9b/RWS_Tarot_07_Chariot.jpg",
"https://upload.wikimedia.org/wikipedia/en/d/db/RWS_Tarot_06_Lovers.jpg",
"https://upload.wikimedia.org/wikipedia/en/d/de/RWS_Tarot_01_Magician.jpg"
];
export default function App() {
const [count, setCount] = useState(0);
const props = useSpring({
opacity: 1,
marginTop: 100,
boxShadow: "0px 100px 20px 0px rgba(0,0,0,0.4)",
from: { opacity: 0, marginTop: 10 }
});
const prevSlide = () => {
let prevSlide = count - 1 < 0 ? cards.length - 1 : count - 1;
setCount(prevSlide);
};
const nextSlide = () => {
let nextSlide = count + 1 < cards.length ? count + 1 : 0;
setCount(nextSlide);
};
return (
<div>
<div className="container">
<animated.div style={props}>
<img src={cards[count]} alt="carousel-img" />
</animated.div>
</div>
<div className="carousel__prev" onClick={prevSlide}>
◀︎
</div>
<div className="carousel__next" onClick={nextSlide}>
▶︎
</div>
</div>
);
}
单击下一步时,如何使动画从顶部淡入图像?
我认为旋转木马的用户术功能比用途弹簧更好。您可以用用户术定义输入并离开动画。当您按下下一个按钮时,必须重叠上一个图像,因此我将位置更改为绝对。页面布局以这种方式改变了。您必须修复它。
export default function App() {
const [count, setCount] = useState(0);
const transitions = useTransition([count], item => item, {
from: { opacity: 0, marginTop: 10, position: 'absolute', boxShadow: "0px 100px 20px 0px rgba(0,0,0,0.4)" },
enter: { opacity: 1, marginTop: 50},
leave: {opacity: 0, marginTop: 100}
});
const prevSlide = () => {
let prevSlide = count - 1 < 0 ? cards.length - 1 : count - 1;
setCount(prevSlide);
};
const nextSlide = () => {
let nextSlide = count + 1 < cards.length ? count + 1 : 0;
setCount(nextSlide);
};
return (
<div>
<div className="container">
{transitions.map(({item, props, key}) => (
<animated.div key={key} style={props}>
{item}
<img src={cards[item]} alt="carousel-img" />
</animated.div>
))}
</div>
<div className="carousel__prev" onClick={prevSlide}>
◀︎
</div>
<div className="carousel__next" onClick={nextSlide}>
▶︎
</div>
</div>
);
}
这是一个代码和盒子示例:https://codesandbox.io/s/image-carousel-with-react-spring-spring-usetransition-q1ndd
i代码和框示例我也引入了反向状态,因为如果我用prev按钮更改动画会感觉更好。