我正在使用React构建实时数据监控应用程序。如果数据值发生变化,我想通过淡入新值来突出显示它。我无法让它上班。以下是我尝试过的内容:
import React from 'react';
export default class ObsValue extends React.PureComponent {
constructor(props) {
super(props);
this.state = {delta: 0};
}
componentWillReceiveProps(newProps) {
const delta = this.props.obsValue - newProps.obsValue;
this.setState(() => {return {delta};});
}
render() {
const str_val = this.props.obsValue.toString();
// If there is a difference, do a fade in to the new value.
const cn = this.state.delta ? "fadeIn" : "";
return (<div className={cn}>{str_val}</div>);
}
}
这是第一次,但不幸的是,此后没有。据推测,问题是在第一次构建组件之后,淡入就完成了。
如何让每个变化的值都淡出来?
我试过的一件事是,只要key
非零,就切换delta
。这向React发出信号,表明这是一个不同的&#34;组件,所以它确实淡入。但是,这似乎有点像黑客。必须有一个更优雅的解决方案。
答案 0 :(得分:-1)
理论上这应该有效,将fadeIn作为你状态中的布尔值,如果发送给你的组件的新道具与之前的道具不同,将设置为true。我应该触发重新渲染,你的fadeIn类应该在每个渲染上显示。希望它有所帮助。
编辑:在setState()回调中添加了超时,如果更新的道具与componentWillReceiveProps()
中的新道具不同,则在0.5秒后将状态fadeIn设置回false。
constructor(props) {
super(props);
this.state = {
fadeIn: false
};
}
componentWillReceiveProps(newProps) {
if (this.props.obsValue !== newProps.obsValue) {
this.setState({ fadeIn: true },
() => setTimeout(() => this.setState({ fadeIn: false }), 500));
}
}
render() {
const str_val = this.props.obsValue.toString();
return (<div className={this.state.fadeIn ? 'fadeIn' : ''}>{str_val}</div>);
}