如何在制表符中动态实现嵌套表格

How to implement nested tables dynamically in tabulator

我正在尝试在制表符中实现嵌套表格,其中数据可以嵌套到 n 级。 我遇到的问题是分配给 rowFormatter 的函数无法看到 createTable() 方法。如何允许回调函数查看 createTable() 函数或我的 class 中的其他函数?

 private createTable(element: HTMLDivElement,jsonFileContents, schemaId: string): Tabulator {
    var table = new Tabulator(this.tab, {
      columns: this.buildHeaders(jsonFileContents, schemaId),
      data: this.buildRows(jsonFileContents, jsonFileContents.schema.find(s => s.parent == null).guid),
      rowFormatter:function(row) {
        var childrenSchemas = jsonFileContents.schemas.filter(s => s.parent == row["schemaId"]);
        if(childrenSchemas){
          childrenSchemas.forEach(schema => {
            var holderEl = document.createElement("div");
            var tableEl = document.createElement("div");
            holderEl.appendChild(tableEl);
            row.getElement().appendChild(holderEl);
            var subTable = this.createTable(tableEl, jsonFileContents, schema.guid); //<---HERE
          });
        }
      }      
    });
  }

您遇到的问题是因为在 rowFormatter 的上下文中 this 指的是 Tabulator table 对象。

因此您可以在定义行格式化程序回调时使用箭头函数,这将保留父级的范围:

rowFormatter:(row) => {

}

或者您可以将 this 的范围存储在不同的变量中,我们将其命名为 self,然后在回调中使用它:

private createTable(element: HTMLDivElement,jsonFileContents, schemaId: string): Tabulator {
    var self = this;

    var table = new Tabulator(this.tab, {
        rowFormatter:function(row) {
            self.createTable();
        }
    });
}