淡出文本,替换文本,然后再次淡出[reactjs]



我有一个p标签列表,我想通过这个列表循环,通过一个p标签淡出,然后淡出,然后在替换它后再次淡出。

这是jQuery中的代码:https://codepen.io/motion333/pen/EBBGVM

我正试图在React中这样做:

useEffect(() => {
(function() {
var quotes = document.getElementsByClassName('tagline-text');
var quoteIndex = -1;
function showNextQuote() {
++quoteIndex;
document.querySelectorAll(".tagline-text")[quoteIndex % quotes.length].fadeIn(1000).delay(1000).fadeOut(1000, showNextQuote);
}
showNextQuote();
})();
}, []);

这是容器:

<div className="tagline h-100 d-flex flex-column align-items-center justify-content-center">
<p className="tagline-text">Your Business</p>
<p className="tagline-text">Your Brand</p>
<p className="tagline-text">Your Content</p>
<p className="tagline-text">Your Portfolio</p>
<p className="tagline-text">You.</p>
</div>

但是它给了我这个错误:

Uncaught TypeError: document.querySelectorAll(...)[(quoteIndex % quotes.length)].fadeIn is not a function

应该可以了

const { useState, useEffect } = React;
const texts = ["Your Business", "Your Brand", "Your Content", "Your Portfolio", "You."];
const time_between_text = 2; // text show for 2s before fade out.
const transition_duration = 0.5;
const App = () => {
const [show, setShow] = useState(0);

useEffect(() => {
const timerId = setInterval(() => {
setShow(p => {
if(p === texts.length - 1) p = -transition_duration;
else p = p + transition_duration;
return p;
});
}, time_between_text * 1000)

return () => clearInterval(timerId);
}, [])
return <div className="pContainer">
{texts.map((t, i) => <p key={i} style={{ opacity: `${show === i ? 1 : 0}`, transitionDuration: `${time_between_text + transition_duration}s` }}>{t}</p>)}
</div>
}
ReactDOM.createRoot(
document.getElementById("root")
).render(
<App />
);
.pContainer {
position: relative;
}
.pContainer p {
font-size: 36px;
font-weight: bold;
position: absolute;
top: 0;
left: 0;
opacity: 0;
transition-property: opacity;
transition-timing-function: ease-in-out;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

最新更新