【发布时间】:2022-02-10 05:23:17
【问题描述】:
我正在使用 React。单击按钮时,文本会发生变化。我想让当前文本淡出,然后在单击按钮时新文本淡入。
我尝试从其他堆栈溢出帖子中实施解决方案,但无济于事。
这里是密码笔https://codepen.io/Jamece/pen/PoObBEN
const duration =1000;
//creating main React component with state being random numbers that will be an index for the quotes and color array.
class QuoteMachine extends React.Component {
constructor(props) {
super(props);
this.state = {
randomIndexQuote: 0,
randomIndexColor: 0,
fadeTransition: null,
fadeState: "fade-in"
};
this.handleClick = this.handleClick.bind(this);
}
//upon click, a random number will be generates and state will be updated
handleClick() {
const timeout = setTimeout(() => {
this.setState({
randomIndexQuote: Math.floor(Math.random() * quotes.length),
randomIndexColor: Math.floor(Math.random() * colors.length),
fadeTransition: null,
fadeState: 'fade-in'
});
}, duration);
clearTimeout(this.state.fadeTransition);
this.setState({
fadeState: "fade-out",
fadeTransition: timeout
});
}
render() {
//variables holding state index
const quoteOutput = quotes[this.state.randomIndexQuote].quote;
const authorOutput = quotes[this.state.randomIndexQuote].author;
//variables for random color styles
const textStyle = {
color: colors[this.state.randomIndexColor],
transition: "all 2s ease"
};
const backgroundStyle = {
backgroundColor: colors[this.state.randomIndexColor],
transition: "all 2s ease"
};
return (
<div className="container-fluid px-0">
<div
className="d-flex justify-content-center align-items-center main"
id="quote-box"
style={backgroundStyle}
>
<div className="white-box">
<div
className={"fade-wrapper ${this.state.fadeState}"}
style={{ transitionDuration: "${duration}ms" }}
>
<p id="text" style={textStyle} className="text-center">
"{quoteOutput}"
</p>
<p id="author" style={textStyle} className="text-end">
{authorOutput}
</p>
</div>
CSS
.fade-wrapper {
transition: opacity ease-in-out;
}
.fade-out {
opacity: 0;
}
.fade-in {
opacity: 1;
}
谢谢。
【问题讨论】:
-
Pure CSS 是无状态的(大多数情况下),所以你将很难协调 CSS 动画与 React 状态。理想情况下尝试使用辅助库。否则,您可以尝试使用 setTimeout 进行编排并匹配动画持续时间。
标签: javascript html css reactjs