【发布时间】:2018-09-22 21:01:55
【问题描述】:
我在 React 应用程序中使用 ag-grid。我们有带有自定义单元格的重型表格。使用构建为 React 组件的自定义单元格渲染器时存在性能问题,这是最直观的论述。
ag-grid 文档指出这可能不是一个好主意:
不要为单元格渲染器使用框架(例如 Angular 或 React)。网格渲染是高度自定义的,纯 JavaScript 单元格渲染器将比框架等效物更快地工作。
但这也表明纯JS可以与React之类的框架结合使用:
使用框架版本的 ag-Grid 仍然可以(例如用于设置 ag-Grid 属性等),但是因为创建和销毁的单元格太多,框架添加的附加层对性能没有帮助,应该如果您有性能问题,请提供。
我误解了吗?在我看来,我可以只使用一个普通的 JS 类作为单元格渲染器(不知何故,也许他们会处理与 React 的集成?)
所以我拿了他们的示例代码并将其转换为一个类而不是一个函数以符合他们的打字稿定义:
// function to act as a class
class MyCellRenderer {
eGui: any;
eButton: any;
eValue: any;
eventListener: any;
init(params: any) {
// create the cell
this.eGui = document.createElement('div');
this.eGui.innerHTML =
'<span class="my-css-class"><button class="btn-simple">Push Me</button><span class="my-value"></span></span>';
// get references to the elements we want
this.eButton = this.eGui.querySelector('.btn-simple');
this.eValue = this.eGui.querySelector('.my-value');
// set value into cell
this.eValue.innerHTML = params.valueFormatted ? params.valueFormatted : params.value;
// add event listener to button
this.eventListener = function() {
// tslint:disable-next-line
console.log('button was clicked!!');
};
this.eButton.addEventListener('click', this.eventListener);
}
// gets called once when grid ready to insert the element
getGui() {
return this.eGui;
}
// gets called whenever the user gets the cell to refresh
refresh(params: any) {
// set value into cell again
this.eValue.innerHTML = params.valueFormatted ? params.valueFormatted : params.value;
// return true to tell the grid we refreshed successfully
return true;
}
// gets called when the cell is removed from the grid
destroy() {
// do cleanup, remove event listener from button
this.eButton.removeEventListener('click', this.eventListener);
}
}
// gets called once before the renderer is used
export default MyCellRenderer;
这构建得很好。现在,当我在应用程序中拉起我的桌子时,我得到了一些可预测的错误:
MyCellRenderer(...):渲染没有返回任何内容。这通常意味着缺少 return 语句。或者,不渲染任何内容,返回 null。
所以它只期待一个 React 组件?看来我无论如何都需要提供渲染操作。
有谁知道这里发生了什么/如何解决这个问题?我是否误解了文档?
谢谢!
附言ag-grid 太棒了!
【问题讨论】:
-
我们能看到 React 标记吗?只需 ag-Grid 渲染和列定义就可以了。刚刚完成了一个和你类似的场景,也许能找到适合你的东西。
-
也有这个问题 - 你找到解决办法了吗?
标签: javascript reactjs ag-grid