【发布时间】:2022-11-29 21:39:50
【问题描述】:
我有一个 React 组件,每个组件显示 5 秒的新报价。我想设置某种过渡,以便它们顺利消失。更准确地说,我将逐步解释我如何看待这种转变:
- 第一个引号开始消失;
- 当它完全消失时,状态变为第二个引号;
- 出现第二个引号;
我认为它可能会随着不透明度的变化而起作用,但我不确定该怎么做。
我有一个带有引号的对象数组,如下所示:
const quotes = [ { id: 0, quote: 'first quote', author: 'first quote author', }, { id: 1, quote: 'second quote', author: 'second quote author', }, { id: 2, quote: 'third quote', author: 'third quote author', }, ]我使用 state 来更改和跟踪当前报价,并使用 useEffect 设置更改状态的时间间隔:
const [currentIndex, setCurrentIndex] = useState(0); const quotesLength = quotes.length - 1; useEffect(() => { const changeIndex = setInterval(() => { setCurrentIndex((prevIndex) => prevIndex < quotesLength ? prevIndex + 1 : 0 ); }, 5000); return () => clearInterval(changeIndex); }, [quotesLength]);我的 JSX 看起来像这样:
return ( <section className="QuoteSection"> {quotes.map((quote) => ( <div className={ currentIndex ? 'quoteWrapper' : 'hidden' } key={quote.id} > <h3 className="quoteText"> {quote.quote} </h3> <p className="quoteAuthor">{quote.author}</p> </div> ))} </section> );这是 CSS:
.QuoteSection { display: flex; flex-direction: column; align-items: center; padding: 6rem; background-color: black; justify-content: center; width: 100%; min-height: 480px; position: relative; } .hidden { display: none; visibility: collapse; } .quoteWrapper { display: flex; flex-direction: column; gap: 2rem; align-items: center; justify-content: center; width: 70%; max-width: 920px; height: 275px; color: white; }我尝试在这里使用动画并且它有点奏效。但它的问题是它不能与状态同步工作。所以有时候它是这样的:
- 报价变更;
- 大约 0.5 秒过去;
- 动画开始,完全相同的引述消失并重新出现。
这是动画:
.quoteWrapper { animation-name: quote-change; animation-duration: 5s; animation-timing-function: ease-in-out; animation-iteration-count: infinite; } @keyframes quote-change { 0% { opacity: 0; } 15% { opacity: 0.8; } 50% { opacity: 1; } 90% { opacity: 0.8; } 100% { opacity: 0; } }
【问题讨论】:
标签: css reactjs react-hooks setinterval