下面的代码过渡或动画不起作用,但图像只是在改变。
styles : {
imageStyle : {
opacity:1,
transition:"opacity 0.5s linear",
height: "304px",
width: "622px",
}
}
const imageBox =() =>{
const images = [ "one.jpeg", "two.jpeg", "three.jpeg", "four.jpeg" ];
const [currentIndex, setCurrentIndex] = useState(0);
return
<>
<img style={styles.imageStyle} src={images[currentIndex]} >
<button onclick={()=>setCurrentIndex(prevState => prevState + 1)}>next image</button>
<>
}
你可以使用react-transition-group
import { useState } from "react";
import "./styles.css";
import { TransitionGroup, CSSTransition } from "react-transition-group";
export default function App() {
const images = [
"https://images.pexels.com/photos/17645273/pexels-photo-17645273/free-photo-of-mode-gens-femme-detente.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
"https://images.pexels.com/photos/17427998/pexels-photo-17427998/free-photo-of-printemps-a-val-gardena.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
"https://images.pexels.com/photos/6142740/pexels-photo-6142740.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
"https://images.pexels.com/photos/17494608/pexels-photo-17494608/free-photo-of-mer-plage-vacances-eau.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
];
const [currentIndex, setCurrentIndex] = useState(0);
const styles = {
imageStyle: {
opacity: 1,
transition: "opacity 0.5s linear",
height: "304px",
width: "422px"
}
};
const handleImageChange = () => {
if (images.length === currentIndex + 1) {
setCurrentIndex(0);
} else {
setCurrentIndex((prevState) => prevState + 1);
}
};
return (
<div className="App">
<h1>Image Slider {currentIndex}</h1>
<TransitionGroup>
<CSSTransition key={images[currentIndex]} timeout={1000}>
<img
style={styles.imageStyle}
alt="Slider"
src={images[currentIndex]}
className="animate"
/>
</CSSTransition>
</TransitionGroup>
<button onClick={() => handleImageChange()}>next image</button>
</div>
);
}
https://codesandbox.io/s/beautiful-torvalds-8ghnjw?file=/src/App.js:0-1645
我刚刚想通了。您可以将 key 属性添加到图像元素,并在想要触发动画时更新其值。