1

我正在尝试将 formik 添加到我使用material-table构建的表格中。有没有办法以另一种方式访问​​ api 以将其与 formik 集成?

这是我正在使用的表格:


import React, { Component } from "react";
import ReactDOM from "react-dom";
import MaterialTable, { FormField, MTableEditRow } from "material-table";
import { Formik, Field, getIn } from "formik";

const FormikField = props => (
  <Field
    name={props.columnDef.field}
    render={({ field, form }) => {
      const { name } = field;
      const { errors, setFieldValue } = form;

      const showError = !!getIn(errors, name);

      return (
        <FormField
          {...props}
          {...field}
          error={showError}
          onChange={newValue => setFieldValue(name, newValue)}
        />
      );
    }}
  />
);

const MuiTableEditRow = ({ onEditingApproved, ...props }) => (
  <Formik
    initialValues={props.data}
    onSubmit={newData => {
      delete newData.tableData;
      onEditingApproved(props.mode, newData, props.data);
    }}
    render={({ submitForm }) => (
      <MTableEditRow {...props} onEditingApproved={submitForm} />
    )}
  />
);

class App extends Component {
  render() {
    return (
      <MaterialTable
        data={[{ id: 1, firstName: "ax", firstName: "Baran" }]}
        columns={[
          { title: "First Name", field: "firstName" },
          { title: "Last Name", field: "lastName" }
        ]}
        editable={{
          onRowAdd: newData =>
            new Promise((resolve, reject) => {
              resolve();
            })
        }}
        components={{
          EditRow: MuiTableEditRow,
          FormField: FormikField
        }}
      />
    );
  }
}

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


4

1 回答 1

2

看起来 EditField 组件可以使用 formik 访问表:

以下是对上述代码的修改:

// imports

...
const FormikMTInput = props => (
   <Field
     name={props.columnDef.field}
     render={({field, form}) => {
       const {name} = field
       const {errors, setFieldValue} = form

       const showError = !!getIn(errors, name)

       return (
         <div>
           <MTableEditField
             {...props}
             {...field}
             error={showError}
             onChange={newValue => setFieldValue(name, newValue)}
           />
           {errors[field.name] && (
             <div style={{color: "#f44336"}}>{errors[field.name]}</div>
           )}
         </div>
       )
     }}
   />
 )

...

const MuiTableEditRow = ({onEditingApproved, ...props}) => (
   <Formik
     validationSchema={courseLevelSchema} // included a validation object
     initialValues={props.data}
     onSubmit={values => {
       delete values.tableData
       onEditingApproved(props.mode, values, props.data)
     }}
     render={({submitForm}) => (
       <MTableEditRow {...props} onEditingApproved={submitForm} />
     )}
   />
 )

... 

<Material

...

 components={{
      EditRow: MuiTableEditRow,
      EditField: FormikMTInput
 }}

...

/>

于 2019-04-12T20:24:45.850 回答