开发者问题收集

使用 useFormik() 与 <Field /> 时出现错误:formik.getFieldProps 不是一个函数

2020-08-08
39273

大家好,我是 formik 库的新手,我正在尝试将 react-draft-wysiwyg 组件与 Formik 结合使用。这是我的代码。

RichTextEditor.js

import React, { useState } from "react";
import { EditorState, convertToRaw, ContentState } from "draft-js";
import { Editor } from "react-draft-wysiwyg";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import draftToHtml from "draftjs-to-html";
import htmlToDraft from "html-to-draftjs";
import { useField } from "formik";

const RichTextEditor = (props) => {
  const [field, meta, helpers] = useField(props);

  const { value } = meta;
  const { setValue } = helpers;

  const prepareDraft = (value) => {
    const draft = htmlToDraft(value);
    const contentState = ContentState.createFromBlockArray(draft.contentBlocks);
    const editorState = EditorState.createWithContent(contentState);
    return editorState;
  };

  const [editorState, setEditorState] = useState(
    value ? prepareDraft(value) : EditorState.createEmpty()
  );

  const onEditorStateChange = (editorState) => {
    const forFormik = draftToHtml(
      convertToRaw(editorState.getCurrentContent())
    );
    setValue(forFormik);
    setEditorState(editorState);
  };

  return (
    <div>
      <Editor
        editorState={editorState}
        wrapperClassName="demo-wrapper"
        editorClassName="demo-editor"
        onEditorStateChange={onEditorStateChange}
        {...props}
        {...field}
      />
    </div>
  );
};

export default RichTextEditor;

AddPost.js

import React from "react";
import { Row, Col, Card, Form, Input } from "antd";
import { useFormik, Field } from "formik";
import RichTextEditor from "../RichTextEditor/RichTextEditor";

const initialValues = {
  title: "",
  body: "",
};
export default function AddContent() {
  const formik = useFormik({
    initialValues,
    onSubmit: (values) => {
      alert(JSON.stringify(values, null, 2));
    },
  });

  return (
    <Row>
      <Col span={19}>
        <Card>
          <>
            <h1>
              {formik.values.title ? formik.values.title : "Content Title"}
            </h1>

            <Form onSubmit={formik.handleSubmit}>
              <Input
                id="title"
                name="title"
                placeholder="Content Title"
                onChange={formik.handleChange}
                value={formik.values.email}
              />

              <Field
                name="body"
                component={RichTextEditor}
                value={formik.values.body}
                onChange={formik.handleChange}
                // {...formik.getFieldProps("body")}
              />
            </Form>
          </>
        </Card>
      </Col>
      <Col span={5}></Col>
    </Row>
  );
}

但是我收到以下错误

TypeError: formik.getFieldProps is not a function
Field
src/Field.tsx:181

  178 |     unregisterField(name);
  179 |   };
  180 | }, [registerField, unregisterField, name, validate]);
> 181 | const field = formik.getFieldProps({ name, ...props });
      | ^  182 | const meta = formik.getFieldMeta(name);
  183 | const legacyBag = { field, form: formik };
  184 | 
3个回答

我遇到了同样的问题,并使用以下修复程序进行了修复。
简而言之,使用 FormikProvider 包装渲染内部。

AddPost.js

// add FormikProvider
import { useFormik, Field, FormikProvider } from "formik";

const formik = useFormik({
  initialValues,
  onSubmit: (values) => {...},
});

// wrap with FormikProvider
return (
  <FormikProvider value={formik}>
    <Row>...your-code...</Row>
  </FormikProvider>
)
Rin
2020-11-04

出现此错误是因为您在 formik 提供的 Field 组件上使用 getFieldProps() 函数,而不是在 Input 等普通组件上使用,这两个组件的工作方式不同。

您应该这样使用它。

<Form onSubmit={formik.handleSubmit}>
    <Input
       id="title"
       placeholder="Content Title"
       {...formik.getFieldProps("title")}
     />

    <Input
       component={RichTextEditor}
       {...formik.getFieldProps("body")}
    />
</Form>

有关 getFieldProps() 的更多信息;

https://formik.org/docs/tutorial#getfieldprops

samo0ha
2021-05-12

如果可以使用 useFormik 钩子创建表单,则需要 <FormikProvider> 组件:

const myForm = useFormik({
  initialValues: {
    name: '',
  },
  onSubmit: ( values ) => {
    console.log(values);
  },
})

return (
  <FormikProvider value={myForm}>
    <Form>
      <Field name="name"/>
    </Form>
  </FormikProvider>
)

或者使用 <Formik> 组件:

import {Field, Formik, Form} from "formik";

return (
  <Formik
    initialValues={{name: ''}}
    onSubmit={values => {
      console.log(values);
    }}
  >
    <Form>
      <label htmlFor="name">Name</label>
      <Field name="name"/>
      <button type="submit">Submit</button>
    </Form>
  </Formik>
)
Keith Davidson
2023-11-04