8

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

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

但是,如果您尝试在外部创建该对象,然后将其分配给查找,您将收到错误消息。

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

提前感谢您的时间,任何指导将不胜感激。

此致

4

3 回答 3

11

我找到了方法,它使用了 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

我希望这对其他人有帮助

此致

于 2019-04-11T17:16:40.200 回答
3

在表之外创建一个对象。

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);
于 2019-04-11T15:45:58.883 回答
0
// 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 }
于 2020-03-20T10:45:20.840 回答