[英]Can't get Formik form to work with Material UI
I'm struggeling with making my Formik form work.我正在努力使我的 Formik 表格正常工作。 Here a part of my code:这是我的代码的一部分:
import { Formik, Form as FormikForm, Field } from "formik";
import {TextField} from "@mui/material";
<Formik
initialValues={{
name: "test",
}}
onSubmit={this.onSubmit}
>
{({ values,handleChange }) => (
<FormikForm>
<Field
component={TextField}
name="name"
label="Name"
fullWidth
></Field>
<Button
color="success"
variant="contained"
type="submit"
onClick={() => {
console.log(values);
}}
>
Erstellen
</Button>
</FormikForm>
)}
</Formik>
It seems like its having trouble connecting the values state to the Field value, since the initialValue isn't displayed in the names field.似乎将值state连接到字段值时遇到了麻烦,因为初始值未显示在名称字段中。 When i submit, it logs {name: 'test'}
to console, no matter what i enter in the input field.当我提交时,无论我在输入字段中输入什么,它都会将{name: 'test'}
记录到控制台。
Edit 1:编辑1:
I also have a very similar form that works.我也有一个非常相似的表格。 The only difference between the two that i can think of is: the working one is a.jsx while this one is.tsx.我能想到的两者之间的唯一区别是:工作的是a.jsx,而这个是.tsx。 Dont know if that has anything to do with it.不知道这和它有没有关系。
According to the Field documentation you need to spread the field
and pass it to the component like this:根据Field 文档,您需要传播field
并将其传递给组件,如下所示:
import { Formik, Form as FormikForm, Field } from "formik";
import { Button, TextField } from "@mui/material";
const MuiTextField = ({ field, form, ...props }) => {
return <TextField {...field} {...props} />;
};
const MyComponent = () => {
return (
<Formik
initialValues={{
name: "test"
}}
onSubmit={(values) => {
console.log(values);
}}
>
{({ values, handleChange }) => (
<FormikForm>
<Field
component={MuiTextField}
name="name"
label="Name"
fullWidth
></Field>
<Button
color="success"
variant="contained"
type="submit"
onClick={() => {
console.log(values);
}}
>
Erstellen
</Button>
</FormikForm>
)}
</Formik>
);
};
export default MyComponent;
You can take a look at this sandbox for a live working example of this solution.您可以查看此沙箱,了解此解决方案的实时工作示例。
Like Ahmet pointed out, the problem seems to be that the field prop needs to be spread (see his answer).就像艾哈迈德指出的那样,问题似乎是需要传播现场道具(见他的回答)。 However i found, that using as instead of component works too and doesnt need spreading.但是我发现,使用as而不是component也可以,不需要传播。
<Field
as={TextField}
name="name"
label="Name"
fullWidth
></Field>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.