首页 > 解决方案 > 未捕获的类型错误:无法读取未定义的属性“setDomLayout”-尝试使打印功能与 AG-Grid 一起使用时出错

问题描述

一直在尝试实现一个在单击时打印 ag-grid 的按钮,如下所示

但是,我在 api.setDomLayout('print') 行的 setPrinterFriendly 处不断收到错误,上面写着 Uncaught TypeError: Cannot read property 'setDomLayout' of undefined。我在这里错过了什么吗?

function setPrinterFriendly(api: any) {
  const eGridDiv = document.querySelector('.my-grid') as HTMLElement;
  eGridDiv.style.width = '';
  eGridDiv.style.height = '';
  api.setDomLayout('print');
}
function setNormal(api: any) {
  const eGridDiv = document.querySelector('.my-grid') as HTMLElement;
  eGridDiv.style.width = '600px';
  eGridDiv.style.height = '200px';
  api.setDomLayout(null);
}

export function onBtPrint(params: any) {
  const gridApi = params.api;
  setPrinterFriendly(gridApi);
  setTimeout(() => {
    print();
    setNormal(gridApi);
  }, 2000);
}
这是我的主要课程项目。

class Items extends Component<any, ItemsState> {
  private gridApi: any;
  constructor(props: any) {
    super(props);
    this.state = {
      columnDefs: [{
        headerName: 'Store', field: 'store', sortable: true, filter: true, resizable: true, minWidth: 100,
      }, {
        headerName: 'Effective Date',
        field: 'effectiveDate',
        sortable: true,
        filter: true,
        resizable: true,
        minWidth: 150,
      },
         ...
  };
}
onGridReady(params: any) {
    params.api.expandAll();
  }


  onGridSizeChanged(params: any) {
    this.gridApi = params.api;
  }

  render() {
    const { rowData } = this.props;

    const {
      columnDefs, rowClassRules, statusBar,
    } = this.state;

    return (
      <div id="grid-wrapper" style={{ width: '100%', height: '100%' }}>
        <button onClick={onBtPrint.bind(null, this)}>Print</button>
        <div
          id="myGrid"
          style={{
            height: '100%',
            width: '98.5%',
            marginLeft: 13,
            overflow: 'scroll',
          }}
          className="ag-theme-balham my-grid"
        >
          <AgGridReact
            columnDefs={columnDefs}
            rowData={rowData}
            onGridReady={this.onGridReady}
            onGridSizeChanged={this.onGridSizeChanged}
            suppressMenuHide
            statusBar={statusBar}
            enableRangeSelection
            rowClassRules={rowClassRules}
            suppressHorizontalScroll={false}
          />
        </div>
      </div>
    );
  }
}

标签: javascriptreactjsag-gridag-grid-react

解决方案


要达到预期结果,请使用以下选项将 params.api 分配给 this.gridApi onGridReady 方法

onGridReady={ params => this.gridApi = params.api } 

请参阅此链接了解更多详情

https://www.ag-grid.com/react-getting-started/


推荐阅读