在 material-table 组件中添加动态信息以查找 属性

Add dynamically info to lookup property in material-table component

我正在尝试动态添加数据以在 Material-Table 组件中查找 属性,但遇到问题。

查找是一个对象,您可以在第一个示例中找到它的定义 https://mbrn.github.io/material-table/#/docz-examples-06-example-filtering

但是,如果您尝试在外部创建该对象,然后将其分配给查找,则会出现错误。

那么,有没有办法将对象数组分配给此查找 属性?

提前感谢您的宝贵时间,如有任何指导,我们将不胜感激。

此致

在 table 之外创建一个对象。

import React from "react";
import ReactDOM from "react-dom";
import MaterialTable from "material-table";
import FilterList from "@material-ui/icons/FilterList";
import Clear from "@material-ui/icons/Clear";
import "./styles.css";

function App() {

  const dynamicLookupObject = { 34: "test1", 63: "test2" }

  // TODO: const createDynamicObject = () => {
       // change object
       // return dynamicLookupObject
     })

  return (
    <div className="App">
      <MaterialTable
        icons={{
          Filter: () => <FilterList />,
          ResetSearch: () => <Clear />
        }}
        columns={[
          { title: "Name", field: "name", defaultFilter: "Meh" },
          { title: "Surname", field: "surname" },
          { title: "Birth Year", field: "birthYear", type: "numeric" },
          {
            title: "Birth Place",
            field: "birthCity",
            lookup: dynamicLookupObject,
            defaultFilter: ["63"], // For numeric,
            emptyValue: () => <div>"dfsdf"</div>
          }
        ]}
        data={[
          { name: "Mehmet", surname: "Baran", birthYear: null, birthCity: 63 },
          {
            name: "Zerya Betül",
            surname: "Baran",
            birthYear: 2017,
            birthCity: 34
          }
        ]}
        title="Filtering Example"
        options={{
          filtering: true,
          maxBodyHeight: 300,
          rowStyle: data =>
            data.surname === "Baran"
              ? { background: "red" }
              : { background: "green" }
        }}
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

我找到了方法,它使用 Reduce,而且效果很好: 假设你有这个对象数组:

  const dinamicObject = [
  { id: 4, name: "name" },
  { id: 2, name: "Mehmet" },
  { id: 3, name: "middle" }
  ];

  var obj = dinamicObject.reduce(function(acc, cur, i) {
  acc[cur.id] = cur.name;
  return acc;
  }, {});

然后将其分配给 Material-Table 组件

中的查找 属性

检查此以获得更多说明https://codesandbox.io/s/vq2lj0krkl

希望对其他人有所帮助

此致

// Suppose you have the following array object from an end point:

const clients = [
    { id: 1, clientname: 'rohit', email: 'rohit@example.com'},
    { id: 2, clientname: 'mohan', email: 'mohan.kumar@example.com'}
]
// Now let us convert it to JavaScript Object with key and value pairs:

const clientOptions = {};
clients.map(client => {
    const { id, email } = client;
    clientOptions[ clientid ] = email
})
// Now look at the output by console.log(clientOptions) , we will get the following output:
// Output:
{ 1 : rohit@example.com, 2 : mohan.kumar@example.com }