这是我的代码库的一个片段 - https://codesandbox.io/s/transition-code-1wr5z
目前,通过更改类和 CSS 过渡,当加载和挂载新的 Paragraph 组件时,文本会淡入。
但是,我希望在段落组件中的文本道具发生变化时也发生这种过渡。
在生命周期内执行此操作更新或渲染只会触发无限更新循环。
不知道从这里开始,因为我能找到的大多数讨论都是关于解决在加载时而不是在更新时让文本淡入的功能。
这是代码片段解决方案
import React, { Component } from "react";
import "./Style.css";
class Paragraph extends Component {
constructor(props) {
super(props);
this.state = {
open: false
};
}
componentDidMount() {
setInterval(() => {
this.fade();
}, 1000);
}
fade() {
this.setState({ open: !this.state.open });
}
render() {
const text = this.props.text;
const classes = this.state.open ? "greenCls" : "redCls";
return <div className={classes}>{text}</div>;
}
}
export default Paragraph;
CSS 类
.redCls {
background: red;
}
.greenCls {
background: green;
}
请尝试使用 setTimeout 来解决此问题
https://codesandbox.io/s/transition-code-fgmyq