React+Redux背景色过渡动画失效问题求助
解决Redux状态更新时背景色过渡动画重复触发问题
问题根源在于:CSS动画默认仅在元素首次应用对应类名时执行一次。即便Redux状态更新导致prevColor和bgColor变化,.bg-fade类的样式虽会更新,但浏览器不会主动重新触发已执行过的动画。以下是两种可行的解决方法:
方案一:利用key属性强制重渲染元素
通过修改元素的key值,让React销毁旧元素并创建新元素,从而重新触发动画。这种方式实现简单,但会重置元素内部组件的状态。
修改后的代码:
const Page = () => { const bgColor = useSelector((reduxState) => reduxState.color) const prevColor = useSelector((reduxState) => reduxState.prevcolor) // 用颜色组合作为key,任一颜色变化都会触发元素重渲染 const animationKey = `${prevColor}-${bgColor}` return <> <style> {` .bg-fade{ background-color: ${prevColor}; animation: transition 1s; animation-fill-mode: forwards; } @keyframes transition { from {background-color: ${prevColor};} to {background-color: ${bgColor};} } `} </style> <main key={animationKey} className='bg-fade'> <div className='container-fluid'> <Gardening /> </div> </main> </> }
方案二:动态添加/移除类名触发动画
通过useEffect监听颜色变化,先移除动画类、强制浏览器重绘后再重新添加类,避免元素重渲染,保留内部组件状态。
修改后的代码:
import { useEffect, useRef } from 'react'; const Page = () => { const bgColor = useSelector((reduxState) => reduxState.color) const prevColor = useSelector((reduxState) => reduxState.prevcolor) const mainRef = useRef(null) useEffect(() => { if (!mainRef.current) return; // 先移除动画类 mainRef.current.classList.remove('bg-fade'); // 强制浏览器重绘,确保类名变化被识别 void mainRef.current.offsetWidth; // 重新添加动画类触发动画 mainRef.current.classList.add('bg-fade'); }, [prevColor, bgColor]) return <> <style> {` .bg-fade{ background-color: ${prevColor}; animation: transition 1s; animation-fill-mode: forwards; } @keyframes transition { from {background-color: ${prevColor};} to {background-color: ${bgColor};} } `} </style> <main ref={mainRef} className='bg-fade'> <div className='container-fluid'> <Gardening /> </div> </main> </> }
内容的提问来源于stack exchange,提问作者balakuz
相关产品推荐
相关产品推荐

