[英]How do I fade in a changing value in React?
我正在使用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發出信號,表明它是一個“不同”的組件,因此它確實淡入了。但是,這似乎有點不合常規。 必須有一個更優雅的解決方案。
從理論上講,這應該可以工作,在您的狀態下將fadeIn作為布爾值,如果您發送給組件的新道具與先前的道具不同,則將其設置為true。 我應該觸發一個重新渲染,並且您的fadeIn類應該顯示在每個渲染上。 希望能幫助到你。
編輯:如果更新的道具與componentWillReceiveProps()
的新道具不同,則在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>);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.