javascript - InitialValues 未显示在 Formik Field 中 Material UI 组件的自动完成中

标签 javascript reactjs material-ui formik

我在从 Formik Field 中使用的 Material UI 库中呈现 AutoComplete 组件中的初始值时遇到问题。作为初始传递的值不会在组件中呈现,尽管事实上如果提交了表单,那么它们将在 values 变量中传递。

如果这个事实很重要,我也会使用 material-ui-formik-components 库。

下面显示的代码提出了这个问题。

import React from "react";
import { Formik, Form, Field } from "formik";
import { object, array } from "yup";
import { Autocomplete } from "material-ui-formik-components/Autocomplete";

const skills = [

  {
    "label": "PostgreSQL",
    "value": "PostgreSQL"
  },
  {
    "label": "Python",
    "value": "Python"
  },
  {
    "label": "React",
    "value": "React"
  },
  {
    "label": "Redis",
    "value": "Redis"
  },
  {
    "label": "Swift",
    "value": "Swift"
  },
  {
    "label": "Webpack",
    "value": "Webpack"
  }
]
const validationSchema = object().shape({
  skills: array().required("At least one skill is required")
});

const initialValues = {
  username: "",
  gender: "",
  country: "",
  skills: [
    {
      label: "PostgreSQL",
      value: "PostgreSQL"
    }
  ],
  birthdate: null
};

const SimpleFormExample = () => (
  <div>
    <h1>Simple Form Example</h1>
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      validateOnBlur={false}
      validateOnChange
      onSubmit={values => {
        console.log(values);
      }}
    >
      {formik => (
        <Form noValidate autoComplete="off">
          <Field
            name="skills"
            options={skills}
            component={Autocomplete}
            textFieldProps={{
              label: "Skills",
              required: true,
              variant: "outlined"
            }}
            multiple
          />

          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);

export default SimpleFormExample;

在 formik 中显示 initialValues 应该怎么做?

最佳答案

import React from "react";
import { Formik, Form, Field } from "formik";
import { object, array } from "yup";
import { Autocomplete } from "material-ui-formik-components/Autocomplete";
import { TextField } from "@material-ui/core";
import { fieldToTextField } from "formik-material-ui";

const skills = [
  {
    label: "PostgreSQL",
    value: "PostgreSQL"
  },
  {
    label: "Pythonaa",
    value: "Pythona"
  },
  {
    label: "React",
    value: "React"
  },
  {
    label: "Redis",
    value: "Redis"
  },
  {
    label: "Swift",
    value: "Swift"
  },
  {
    label: "Webpack",
    value: "Webpack"
  }
];
const validationSchema = object().shape({
  skills: array().required("At least one skill is required")
});

const initialValues = {
  username: "abc",
  gender: "",
  country: "",
  skills: [
    {
      label: "Swift",
      value: "Swift"
    },
    {
      label: "Webpack",
      value: "Webpack"
    }
  ],
  birthdate: null
};

const FormikAutocomplete = ({ textFieldProps, ...props }) => {
  const {
    form: { setTouched, setFieldValue }
  } = props;
  const { error, helperText, ...field } = fieldToTextField(props);
  const { name } = field;

  return (
    <Autocomplete
      {...props}
      {...field}
      onChange={(_, value) => setFieldValue(name, value)}
      onBlur={() => setTouched({ [name]: true })}
      getOptionSelected={(item, current) => item.value == current.value}
      renderInput={props => (
        <TextField
          {...props}
          {...textFieldProps}
          helperText={helperText}
          error={error}
        />
      )}
    />
  );
};

const SimpleFormExample = () => (
  <div>
    <h1>Simple Form Example</h1>
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      validateOnBlur={false}
      validateOnChange
      onSubmit={values => {
        console.log(values);
      }}
    >
      {formik => (
        <Form>
          <Field
            name="skills"
            component={FormikAutocomplete}
            label="Skills"
            options={skills}
            textFieldProps={{
              fullWidth: true,
              margin: "normal",
              variant: "outlined"
            }}
            multiple
          />

          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);

export default SimpleFormExample;

你可以查看我的codesandbox https://codesandbox.io/s/optimistic-kare-9wqfq?file=/src/Component.tsx:0-2327

您还可以更改 AutoComplete 的 getOptionSelected 属性来确定是否选择了一个选项。

关于javascript - InitialValues 未显示在 Formik Field 中 Material UI 组件的自动完成中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61125310/

相关文章:

javascript - 仅在浏览器完全重定向后才调用该函数?

javascript - html5 视频标签在 android phonegap 中不起作用

javascript - React Native - Undefined 不是对象(评估 this.props.isLoggedIn.then)

html - 如何使用 css 修复左侧网格中存在的顶部栏而不将其重叠到下一个右侧网格元素?

reactjs - 单击自动完成 Material UI 的按钮时如何删除选定的值?

javascript - 将基本 URL 重定向到主页

javascript - requestAnimationFrame "Uncaught Type"错误

javascript - 更新 React.js 组件中的状态在我的页面下留下空白

reactjs - 子组件列表未渲染

reactjs - 如何使用 styled-components 将 prop 传递给 Material-UI 组件