简体   繁体   中英

How do I fade in a changing value in React?

I am building a real-time data monitoring app using React. If a data value changes, I want to highlight it by fading in the new value. I'm having trouble getting it to work. Here's what I've tried:

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>);
    }
}

This works the first time, but, unfortunately, not thereafter. Presumably the problem is that after the first time the component has been built, so the fade in is complete.

How do I get it to fade in with every changing value?

One thing I tried was to toggle a key whenever delta was non-zero. This signaled to React that this was a "different" component, so it did the fade in. But, this seems like a bit of a hack. There must be a more elegant solution.

In theory this should work, having fadeIn as a boolean in your state that will be set to true if the new props you send to your component is different from the previous ones. I should trigger a re-render and your fadeIn class should be shown on each render. Hope it helps.

EDIT: Added a timeout in the setState() callback to set state fadeIn back to false after 0.5 second if the updated props is different from the new props in componentWillReceiveProps() .

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>);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM