首页 文章

ag-grid CellRenderer - 当其他行数据(props.data)发生变化时如何呈现?

提问于
浏览
3

我想基于与行绑定的 props.data 对象中可用的其他数据,以某种方式呈现单元格 . 但是,当其他数据发生变化时,我无法弄清楚如何让单元格重新渲染 .

我有一个非常简单的数据结构我试图在ag-grid中显示,基本上是一个属性数组,每个都有一个名称,一个值和一个isLoading标志,指示属性是否正在更新(如后台刷新)可能会发生,网格单元格中的数据是只读的) .

我希望网格显示名称和值列,如果 isLoading == true ,我希望值列显示微调器图标 .
我正在尝试为此构建自定义单元格渲染器,但单元格仅在值更改时重新渲染,而不是在isLoading标志更改时重新渲染 .

在我的代码流程中,isLoading标志设置为true,然后更新该值 . 这将触发render方法,单元格现在将显示更新的值和加载微调器 . 然后isLoading标志设置为false,但不再调用render方法,因此单元格继续显示加载微调器 .

所以我的问题是,我怎样才能让一个cellrenderer响应 props.data 中的变化,而这些变化不适用于它所显示的值的字段?在这种情况下,我需要在 props.data.isLoading 标志更改时重新呈现单元格 .

我正在使用ag-grid v17 with react和redux(并尝试打字稿) .
我的代码看起来非常类似于这里的示例:https://www.ag-grid.com/react-redux-integration-pt1/

我的单元格渲染器是在此示例中使用货币渲染器构建的:https://www.ag-grid.com/javascript-grid-cell-rendering-components/#example-rendering-using-react-components

注意:我将网格的deltaRowDataMode设置为true,因此它只重新呈现已更改的数据 .

这是我的列定义:

{
    colId: 'value',
    headerName: 'Value',
    field: 'value',  //the property's value on my data structure
    cellRendererFramework: MyCellRenderer
}

这是我的单元格渲染器:

import React from 'react';
import { ICellRendererParams } from 'ag-grid';

interface RendererState {
    currentValue: string;
    isLoading: boolean;
}

export class MyCellRenderer extends React.Component<ICellRendererParams, RendererState> {
    constructor(props: ICellRendererParams) {
        super(props);
        this.state = { currentValue: props.data.value, isLoading: props.data.isLoading };
    }

    //refresh is only called when the value changes, not when params.data.isLoading changes, so render does not get called
    refresh(params: ICellRendererParams) {
        if (params.value !== this.state.currentValue) {
            this.setState({ currentValue: params.value });
        }
        if (params.data.isLoading !== this.state.isLoading) {
            this.setState({ isLoading: params.data.isLoading });
        }
        return true;
    }

    render() {
        var loadingStyle = {
            display: (this.state.isLoading) ? '' : 'none'
        };
        return (
            <div>
                {this.state.currentValue}
                <div className="pull-right">
                    <span className="fa fa-refresh fa-spin" style={loadingStyle}></span>&nbsp;
                </div>
            </div>
        );
    }

}

这也可以使用单元格类或样式,但是我还希望能够以类似的方式处理其他事情,例如使用带按钮的单元格渲染器,并且如果isLoading是,则禁用该按钮真正 .

Update:
在这里添加了一个工作示例:https://react-owixbq.stackblitz.io/

1 回答

  • 0

    而不是在refresh()内更新状态,请尝试使用componentWillReceiveProps .

    componentWillReceiveProps(nextProps){
            if(nextProps.data.yourField !== this.props.data.yourField){
                this.setState({ isLoading: false, currentValue: nextProps.data.yourField });
            }
        }
    

相关问题