我正在尝试使用每次用户在图像轮播中单击下一步时页面加载时最初使用的动画。
我尝试使用类似于以下的反应弹簧:
const springs = useSprings(cards.map(item => ({ opacity: item.opacity }))
但是我收到“ TypeError:无法读取未定义的属性'0'”
这在使用useSpring(非复数)时有效:
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>
);
}
当单击下一步时,如何使动画从顶部淡入图像?
答案 0 :(得分:0)
我认为对于转盘来说,useTransition函数比useSprings更好。您可以使用useTransition定义进入和离开动画。当您按下next按钮时,上一张和下一张图像必须重叠,因此我将位置更改为绝对位置。这样,页面布局发生了一些变化。您必须修复它。
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>
);
}
这是一个codeSandbox示例:https://codesandbox.io/s/image-carousel-with-react-spring-usetransition-q1ndd
在codesandbox示例中,我还介绍了一种反转状态,因为如果使用prev按钮更改动画会感觉更好。