簡體   English   中英

如何讓 Material-UI DataGrid valueGetter 從數組中不同的 object 讀取數據?

[英]How can I get the Material-UI DataGrid valueGetter to read data from a distinct object in an array?

我正在為 Woocommerce 開發 React 管理頁面。我想從特定的 object(名稱為“Farbe”的產品屬性)檢索“選項”值以顯示在 MUI DataGrid 中。 我認為 valueGetter 是正確的方法,但無法讓它發揮作用。

這是我所擁有的:

Woocommerce Product(行記錄):

    {
       "id": 232,
       "date_created": "2022-08-14T08:02:18",
       ...
       "attributes": [
          {
             "id": 0,
             "name": "Farbe",
             "option": "0045"
          },
          {
             "id": 1,
             "name": "Material",
             "option": "Cotton"
          },
          ...
       ],
       ...
    }

DataGrid 列:我正在嘗試 select object 在鍵“名稱”上具有值“Farbe”並訪問屬性“選項”的值

export const VariationColumns  = [
    { field: 'id',   headerName: 'Id',   type: 'int', width: 100},
    { field: 'sku',  headerName: 'SKU',  type: 'string', width: 200},
    { field: 'name', headerName: 'Name', type: 'string', width: 500, 
       valueGetter: ( params ) => { return params.row.attributes[name =>'Farbe'].option }},
]

但它找不到“選項”屬性: “TypeError:無法讀取未定義的屬性(讀取“選項”)”

還嘗試過:

valueGetter: ( params ) => { return params.row.attributes[name =>'Farbe'].option.value
valueGetter: ( params ) => { return params.row.attributes.name['Farbe'].option
valueGetter: ( params ) => { return params.row.attributes.name['Farbe'].option.value

是否可能需要一種完全不同的方法來實現這一目標? 非常感謝任何提示

假設你的rows道具看起來像你上面提供的記錄,你會得到這樣的:

const rows = [
    {
      id: 232,
      date_created: "2022-08-14T08:02:18",
      attributes: [
        {
          id: 0,
          name: "Farbe",
          option: "0045",
        },
        {
          id: 1,
          name: "Material",
          option: "Cotton",
        },
      ],
    },
  ];

const variationColumns = [
    { field: "id", headerName: "Id", type: "int", width: 100 },
    { field: "sku", headerName: "SKU", type: "string", width: 200 },
    {
      field: "attributes",
      headerName: "Name",
      type: "string",
      width: 500,
      valueGetter: (params) => {
        return params.value.find((item) => item.name === "Farbe").option;
      },
    },
  ];

關鍵點是:

  1. valueGetter參數是單元格參數與行參數
  2. 列中的field屬性需要與rows中的字段匹配,因此如果要獲取attributes ,則需要在列中包含field: "attributes"
  3. 您可以使用params.value.find((item) => item.name === "Farbe").option)返回數組中與所需搜索字符串匹配的 object,然后訪問其option屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM