我正在使用 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>);
}
}
这第一次有效,但不幸的是,之后就不行了。据推测,问题是在第一次构建组件后,淡入就完成了。
如何让它随着每个变化的值淡入淡出?
我尝试的一件事是每当 delta
不为零时切换 key
。这向 React 发出信号,表明这是一个“不同的”组件,因此它会淡入。但是,这似乎有点 hack。一定有更优雅的解决方案。
最佳答案
理论上这应该可行,如果您发送到组件的新 Prop 与以前的 Prop 不同,则将 fadeIn 作为您状态中的 bool 值将设置为 true。我应该触发重新渲染,并且您的 fadeIn 类应该显示在每个渲染上。希望对您有所帮助。
编辑:如果更新的 Prop 与 componentWillReceiveProps()
中的新 Prop 不同,则在 setState() 回调中添加超时以在 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>);
}
关于javascript - 我如何在 React 中淡入变化的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48423020/