tengo este código que reemplaza el índice en la matriz cada 5 segundos para mostrar un texto diferente
const [articles, setArticles] = useState(0) const [imageBanner, setImageBanner] = useState([ { text: "blah blah" }, { text: "blah blah" }, {} ]) setInterval(() => { if (articles < 3) { setArticles(articles => articles + 1) } console.log(articles) }, 5000);y me gustaría saber cómo puedo hacer una animación de opacidad cuando se reemplaza el texto
lo que probé antes
@keyframes example { 0% { opacity: 0; } 3% { opacity: 0.2; } 6% { opacity: 0.4; } 8% { opacity: 0.6; } 10% { opacity: 0.8; } 50% { opacity: 1; } 90% { opacity: 0.8; } 93% { opacity: 0.6; } 96% { opacity: 0.4; } 98% { opacity: 0.2; } 100% { opacity: 0; }}
Pero el momento no es bueno.
En lugar de usar un setInterval , use el tiempo de la animación para cambiar el texto del elemento.
Usando un gancho useRef podemos crear una referencia a nuestro elemento de animación. Luego escuche el evento de iteración de animationiteration en ese elemento. Este evento se activará cada vez que comience de nuevo.
Para que esto funcione, necesitaremos modificar la animación CSS y decirle que vaya N veces o infinite veces.
Cuando se llama al evento, use setArticleIndex para contar hasta el siguiente elemento (o hasta 0 cada vez que se alcance el final de la lista).
const { useRef, useState, useEffect } = React; const imageBanners = [ { text: "Hello There" }, { text: "General Kenobi" }, { text: "You are a bold one" } ]; const Component = () => { const animationEl = useRef(null); const [articleIndex, setArticleIndex] = useState(0); useEffect(() => { animationEl.current.addEventListener('animationiteration', () => { setArticleIndex(currentIndex => { if (currentIndex + 1 < imageBanners.length) { return currentIndex + 1; } else { return 0; } }); }); }, []); return ( <div className="fade-in-out" ref={animationEl}> {imageBanners[articleIndex].text} </div> ); }; const app = document.querySelector('#app'); ReactDOM.render( <Component />, app ); @keyframes fade-in-out { 0% { opacity: 0; } 5%, 95% { opacity: 1; } 100% { opacity: 0; } } .fade-in-out { animation: fade-in-out 5s both infinite; } <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="app"></div>Este código debería funcionar usando animation y animation-fill-mode .
@keyframes move { from { opacity: 0; } 3% { opacity: 0.2; } 6% { opacity: 0.4; } 8% { opacity: 0.6; } 10% { opacity: 0.8; } 50% { opacity: 1; } 90% { opacity: 0.8; } 93% { opacity: 0.6; } 96% { opacity: 0.4; } 98% { opacity: 0.2; } to { opacity: 0; } } h1 { animation-name: move; animation-delay: 0s; animation-duration: 5s; animation-timing-function: linear; animation-iteration-count: infinite; } <h1>Hello, World</h1>