【问题标题】:ag-Grid Cell Rendering - Custom Propsag-Grid 单元格渲染 - 自定义道具
【发布时间】:2017-10-25 07:07:51
【问题描述】:

查看ag-Grid Cell Rendering documentation 后,我看不到通过cellRenderFramework 参数向单元格渲染器添加自定义属性的方法。例如,我想将一个回调传递给我的自定义渲染器,该渲染器在单击按钮时被调用。

class AddCellRenderer extends React.Component<ICellRendererParams, {}> {

  /**
   * Callback handle to pass data to on a click.
   */
  public static callback = (data: MyData): void => { return; };

  public constructor(params: ICellRendererParams) {
    super(params);
  }

  public render() {
    let className = 'pt-button pt-intent-success pt-icon-add';
    let text = 'Click to add';
    if (this.props.data.saved) {
      className = 'pt-button pt-intent-danger pt-icon-remove';
      text = 'Click to remove';
    }
    return (
      <button type="button" onClick={this.onClick} className={className}>{text}</button>
    );
  }

  private onClick = (event: React.FormEvent<HTMLButtonElement>): void => {
    AddCellRenderer.callback(this.props.data);
    this.setState({ ...this.state }); // Make React update the component.
  }
}

我还有另一个组件像这样使用它

public render() {
  let saveCellRenderer = AddCellRenderer;
  saveCellRenderer.callback = this.onSelectData;
  const columnDefs: ColDef[] = [
    {
      headerName: 'Add to Available Data',
      cellRendererFramework: AddCellRenderer,
    },
    ...
  ];
  ...
  }

除了一个丑陋的静态公共方法之外,必须有另一种方法将此回调作为 props 传递,当多个组件使用渲染器时将无法工作,我该如何使用 ag-Grid 执行此操作?

【问题讨论】:

  • 最终使用高阶组件来帮助解决这个问题。

标签: javascript reactjs typescript ag-grid


【解决方案1】:

我知道这已经晚了。但是你试过cellRendererParamscellRenderer吗?
您可以使用它为自定义单元组件设置自定义道具。例如:

columnDef = [
    .......
    {
        .......
        cellRenderer: CustomCellComponent,
        cellRendererParams: {
            prop1: "this is prop1"
        }
    }
]

【讨论】:

  • 只是补充一点,您仍然可以使用 CellRendererParams 中定义的现有参数,例如 valuedata。只需要在 prop 定义中指向它们。
  • 相关文档herehere。请注意,对于 headerComponentFramework 渲染器,您需要改为传递 headerComponentParams
  • 添加cellRendererParams后,如何在CustomCellComponent 内访问?请帮忙。
  • @StangSpree 它应该在 CustomCellComponent 的 props (props.prop1) 中可用。
  • @JollyGood 我不明白为什么不这样做。