javascript - 我如何在 React 中淡入变化的值?

标签 javascript css reactjs

我正在使用 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/

相关文章:

javascript - 代理 : Calling static methods of target's parent when using a proxy object

javascript - 在不改变文档流程的情况下描绘 HTML 部分

css - 如何使用 div 和 span(而不是表格标签)设计网站

reactjs - 如何将Create-react-app与passport中间件集成?

reactjs - 如何在 React 中使用 refs with Typescript

javascript - 展开时沿 TreeView 添加垂直线

javascript - 为什么 GitHub 会在我的 jekyll 站点上附加一个 js

css - 如何在 sass 中嵌入 css,或者在 sass 中使用 + 选择器?

html - SCSS/CSS 最近父级选择器

reactjs - 我的模拟函数在 Sagas 测试中没有被调用