我可以将FieldArray与useFormik挂钩一起使用吗?

时间:2020-01-30 06:16:33

标签: reactjs formik

在表单组件中,我想将FieldArray与useFormik挂钩一起使用。当我尝试这样做时,会出现TypeError: _this$props2$formik is undefined错误。

我应该切换到类组件,还是可以以某种方式将Formik注入到FieldArray?还是有办法做到?

const MyForm = ({openPanel}) => {
    const intl = useIntl();

    const formData = useSelector(state => state.form[Forms.SOURCE_EDIT]);

    const formik = useFormik({
        initialValues: {
            style: formData ? formData.style : '',
            layers: formData ? formData.layers : [],
        },
        validationSchema: createValidationSchema(),
        onSubmit: async values => {
            // ...
        },
    });

    const {
        values,
        errors,
        touched,
        handleSubmit,
        isSubmitting,
        handleChange,
        handleBlur,
    } = formik;

    return (
        <div className={'center-flex'}>
            <form onSubmit={handleSubmit}>
                {/* ... */}
                <FieldArray
                    name={'layers'}
                    render={arrayHelpers => (
                        <div>
                            {values.layers.map((layer, index) => (
                                <div key={index}>{layer.name}</div>
                            ))}
                        </div>
                    )}
                />
                <Button
                    large
                    intent={Intent.PRIMARY}
                    fill
                    loading={isSubmitting}
                    disabled={isSubmitting}
                    type={'submit'}>
                    {intl.formatMessage(messages.next)}
                </Button>
            </form>
        </div>
    );
};

预先感谢

3 个答案:

答案 0 :(得分:4)

如formik文档中所述:**请注意,<Field><FastField><ErrorMessage>connect()<FieldArray>不适用于{{ 1}},因为它们都需要React Context。 您必须将表单包装在useFormik()组件中,以便在内部使用formik上下文时使用这些组件。供参考:https://jaredpalmer.com/formik/docs/api/useFormik

答案 1 :(得分:1)

可能有点晚了,但是您可以使用FormikProvider,它以useFormik值作为道具。

const formik = useFormik()
....
<FormikProvider value={formik}>
  <FieldArray name="" render={() => (...) />
</FormikProvider>

答案 2 :(得分:0)

你也可以使用

https://ramdajs.com/docs/#symmetricDifferencehttps://lodash.com/docs/4.17.15#xor

const { values, handleSubmit, handleChange, handleBlur, setFieldValue, errors } = useFormik({

const handleBerthTypeChange = React.useCallback<NonNullable<CheckboxProps["onChange"]>>(
  (e) => {
    setFieldValue("berthTypes", symmetricDifference(values.berthTypes ?? [], [e.target.name]));
  },
  [values, setFieldValue],
);


<Checkbox
  checked={values.berthTypes?.includes(code) ?? false}
  onChange={handleBerthTypeChange}
  name={code}
/>