如何使用 blueprintjs/table 渲染 table

How to render a table with blueprintjs/table

我正在尝试在 blueprintjs table 中显示 json 数据数组。 table 在渲染时应该是动态的(行数和列数),以便显示 json 数组中的任何内容。在生产中,json 数组将来自 API 调用,但首先,我只是想让它处理一些虚拟数据。

我已经设法动态生成 table 并显示列 headers,但是我仍然无法生成实际的数据单元格。

到目前为止,这是我的代码:

interface ResultsTableProps {}
interface ResultsTableState {
    numResultsRows? : number,
    results
}

export default class ResultsTable extends React.Component 
<ResultsTableProps, ResultsTableState> {

    public state: ResultsTableState = {
        numResultsRows: 0,
        results: null
    }

    componentDidMount() {
        var searchString = store.getState().submitSearch.searchString;

        // Pretend an API call just happened and the results object is returned

        // This is the dummy data
        var resultsObject = getData();
        this.setState({
            numResultsRows: resultsObject.length,
            results: resultsObject
        });
    }

    private createColumn(columnData) {
        return <Column name={columnData} />
    }

    private createColumns(columnDatas) {
        return Object.keys(columnDatas[0]["_source"]).map(this.createColumn);
    }

    private createTable(results, numResultsRows) {
        return (
            <Table numRows={numResultsRows}>
                {this.createColumns(results)}
            </Table>
        );
    }

    render() {
        return (            
            <div id="results-table">
                <Card interactive={false} elevation={Elevation.TWO} className={"pt-dark"}>
                    {this.createTable(this.state.results, this.state.numResultsRows)}
                </Card>
            </div>
        );
    }
}

当这段代码运行时,我得到一个 table,其中包含正确的行数和正确的列数,以及正确的列 headers。

我现在需要以某种方式用 cells/data 填充行,但我被卡住了。我不确定我应该怎么做。

如何做到?

如果您想查看虚拟数据:

[
{
    "_type": "location",
    "_id": "5sXFcmEBsayGTsLx1BqB",
    "_source": {
      "elevation": "",
      "country": "ZA",
      "geonameid": "958386",
      "timezone": "Africa/Johannesburg",
      "latitude": "-27.17494",
      "mod_date": "2014-10-01",
      "dem": "968",
      "admin1_fips": "08",
      "population": "0",
      "alternatenames": "",
      "feature_class": "S",
      "geohash": "k7pt6ubwx0n0",
      "name": "Sahara",
      "alt_cc": "",
      "fulltext": "ZA 958386 Africa/Johannesburg -27.17494 2014-10-01 968 08 0  S Sahara  DC8 Sahara FRM NC083 21.91872",
      "admin2": "DC8",
      "asciiname": "Sahara",
      "feature_code": "FRM",
      "admin3": "NC083",
      "longitude": "21.91872",
      "admin4": ""
    }
}
]

注意我只对显示 _source 键中的数据感兴趣。所以我的列的名称是 "elevation"、"country"、"geonameid" 等。单元格数据应该是这些键的值。我的真实虚拟数据实际上在数组中有大约 20 个 objects,但为了简洁起见,我只显示了一个。

可以传递键和值,而不是只传递它们的键:

 private createColumns(columnDatas) {
    return Object.entries(columnDatas[0]["_source"]).map(this.createColumn);
 }

现在你可以这样获取:

private createColumn([key, value]) {
  //...
}

这是一个更完整的例子。

    const data = [
      {foo: {bar: "baz"}},
      ...
    ]

// allows access to a deep object property by name
const getNestedProp = (obj, path) => (
  path.split('.').reduce((acc, part) => acc && acc[part], obj)
)

const objectCellRenderer = (key) => (rowIndex) => {
    return <Cell>{getNestedProp(data[rowIndex], key)}</Cell>

渲染 table 时,像这样定义列 cellRenderer:

<Column name="someColumn" cellRenderer={objectCellRenderer("foo.bar")}/>

你只是缺少 cellRenderer prop.

const createCell = (columnData) => (rowIndex) => {
    return (
      <Cell key={""}>{data[rowIndex][columnData]}</Cell>
    );
  };

完成code=>

const SomeTable = () => {
  const [data, setData] = useState("");
  const [numDataRows, setNumDataRows] = useState(0);

  useEffect(() => {

    return 
      let fetchedData = []
// here you fetch data from somewhere
      ...
      setData(fetchedData);
      setNumDataRows(fetchedData.length);
    });
  }, []);

  const createCell = (columnData) => (rowIndex) => {
    return (
      <Cell key={rowIndex + columnData}>{data[rowIndex][columnData]}</Cell>
    );
  };

  const createColumn = (columnData, colIndex) => {
    return (
      <Column
        name={columnData}
        key={colIndex}
        cellRenderer={createCell(columnnData)}
      />
    );
  };

  const createColumns = (columnsData) => {
    return columnsData ? Object.keys(columnsData[0]).map(createColumn) : [];
  };

  const CreateTable = (data, numDataRows) => {
    return (
      <Table numRows={numPlayersRows}>
        {createColumns(data)}
      </Table>
    );
  };

  return <>{CreateTable(data, numDataRows)}</>;
};

export default SomeTable;