4

我正在做一个项目,我基本上使用材料表界面进行 crud。我想知道是否有办法让我也想填写必填字段?

我尝试研究但没有太多结果。请参阅下面的代码,该代码直接来自https://material-ui.com/components/tables/最后一个示例。当然,我已经修改了我的代码库以供我个人使用,一切正常,但我不确定如果我也想要,如何制作必填字段?如果是,我会怎么做?我会在 MaterialTable 上传递一些东西作为道具选项吗?

感谢您的任何建议。

import React from 'react';
import MaterialTable from 'material-table';

export default function MaterialTableDemo() {
  const [state, setState] = React.useState({
    columns: [
      { title: 'Name', field: 'name' },
      { title: 'Surname', field: 'surname' },
      { title: 'Birth Year', field: 'birthYear', type: 'numeric' },
      {
        title: 'Birth Place',
        field: 'birthCity',
        lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
      },
    ],
    data: [
      { name: 'Mehmet', surname: 'Baran', birthYear: 1987, birthCity: 63 },
      {
        name: 'Zerya Betül',
        surname: 'Baran',
        birthYear: 2017,
        birthCity: 34,
      },
    ],
  });

  return (
    <MaterialTable
      title="Editable Example"
      columns={state.columns}
      data={state.data}
      editable={{
        onRowAdd: newData =>
          new Promise(resolve => {
            setTimeout(() => {
              resolve();
              const data = [...state.data];
              data.push(newData);
              setState({ ...state, data });
            }, 600);
          }),
        onRowUpdate: (newData, oldData) =>
          new Promise(resolve => {
            setTimeout(() => {
              resolve();
              const data = [...state.data];
              data[data.indexOf(oldData)] = newData;
              setState({ ...state, data });
            }, 600);
          }),
        onRowDelete: oldData =>
          new Promise(resolve => {
            setTimeout(() => {
              resolve();
              const data = [...state.data];
              data.splice(data.indexOf(oldData), 1);
              setState({ ...state, data });
            }, 600);
          }),
      }}
    />
  );
}
4

4 回答 4

7

Material-table 具有对验证的本机支持,可以轻松地用于使字段成为必需。您所要做的就是validation根据此处的文档指定列规范中的字段:https ://material-table.com/#/docs/features/validation 。

这是您的代码的样子,例如,如果您想让“姓氏”成为必需:

...
  const [state, setState] = React.useState({
    columns: [
      { title: 'Name', field: 'name' },
      {
          title: 'Surname',
          field: 'surname',
          validate: rowData => Boolean(rowData.surname),
      },
      { title: 'Birth Year', field: 'birthYear', type: 'numeric' },
      {
        title: 'Birth Place',
        field: 'birthCity',
        lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
      },
    ],
    data: [
      { name: 'Mehmet', surname: 'Baran', birthYear: 1987, birthCity: 63 },
      {
        name: 'Zerya Betül',
        surname: 'Baran',
        birthYear: 2017,
        birthCity: 34,
      },
    ],
  });
...

ps 除非它会发生变化,否则无需将您的columns数据置于此处的状态,这在这种情况下似乎不太可能。

于 2020-11-30T10:29:50.823 回答
3

@HereticMonkey 的评论基本上解决了我的问题。

需要的字段是通过可编辑的组件完成的,如 Heretic Monkey 所示的示例 ^^。

谢谢

于 2019-09-18T13:21:28.753 回答
3

您需要在 onRowAdd 和 onRowUpdate 上使用 editComponent、TextField 和验证处理。

请参阅下面的示例修改代码。

import React from "react";
import MaterialTable from "material-table";
import TextField from "@material-ui/core/TextField";

export default function App() {

const [nameError, setNameError] = React.useState({
    error: false,
    label: "",
    helperText: "",
    validateInput: false,
});

const columnsHeader = [
    {
        title: "Name",
        field: "name",
        editComponent: (props) => (
            <TextField
                type="text"
                error={
                    !props.value &&
                    nameError.validateInput &&
                    props.rowData.submitted
                        ? nameError.error
                        : false
                }
                helperText={
                    !props.value &&
                    nameError.validateInput &&
                    props.rowData.submitted
                        ? nameError.helperText
                        : ""
                }
                value={props.value ? props.value : ""}
                onChange={(e) => {
                    if (nameError.validateInput) {
                        setNameError({
                            ...nameError,
                            validateInput: false,
                        });
                    }

                    props.onChange(e.target.value);
                }}
            />
        ),
    },
    { title: "Surname", field: "surname" },
    { title: "Birth Year", field: "birthYear", type: "numeric" },
    {
        title: "Birth Place",
        field: "birthCity",
        lookup: { 34: "İstanbul", 63: "Şanlıurfa" },
    },
    { title: "submitted", field: "submitted", hidden: true },
];

const [state, setState] = React.useState({
    data: [
        {
            name: "Mehmet",
            surname: "Baran",
            birthYear: 1987,
            birthCity: 63,
            submitted: false,
        },
        {
            name: "Zerya Betül",
            surname: "Baran",
            birthYear: 2017,
            birthCity: 34,
            submitted: false,
        },
    ],
});

return (
    <MaterialTable
        title="Editable Example"
        columns={columnsHeader}
        data={state.data}
        editable={{
            onRowAdd: (newData) =>
                new Promise((resolve, reject) => {
                    setTimeout(() => {
                        newData.submitted = true;
                        if (!newData.name) {
                            setNameError({
                                error: true,
                                label: "required",
                                helperText: "Name is required.",
                                validateInput: true,
                            });
                            reject();
                            return;
                        }
                        resolve();

                        const data = [...state.data];
                        data.push(newData);
                        setState({ ...state, data });
                    }, 600);
                }),
            onRowUpdate: (newData, oldData) =>
                new Promise((resolve, reject) => {
                    setTimeout(() => {
                        newData.submitted = true;
                        if (!newData.name) {
                            setNameError({
                                error: true,
                                label: "required",
                                helperText: "Name is required.",
                                validateInput: true,
                            });
                            reject();
                            return;
                        }
                        resolve();
                        const data = [...state.data];
                        data[data.indexOf(oldData)] = newData;
                        setState({ ...state, data });
                    }, 600);
                }),
            onRowDelete: (oldData) =>
                new Promise((resolve) => {
                    setTimeout(() => {
                        resolve();
                        const data = [...state.data];
                        data.splice(data.indexOf(oldData), 1);
                        setState({ ...state, data });
                    }, 600);
                }),
        }}
    />
);

}

于 2020-04-27T16:01:32.140 回答
1

只需像这样验证和使用 Reject() (调用 reject() 保持打开的行可编辑):

 onRowAdd: (newData) =>
        new Promise((resolve) => {
          if(---!validate(newData)---) {
            // alert('required');
            reject();
          }else{ /*addRow*/ }
于 2020-04-20T06:20:48.307 回答