问题:React Formik 在 <Formik /> 外使用 submitForm

当前行为

<Formik
    isInitialValid
    initialValues={{ first_name: 'Test', email: 'test@mail.com' }}
    validate={validate}
    ref={node => (this.form = node)}
    onSubmitCallback={this.onSubmitCallback}
    render={formProps => {
        const fieldProps = { formProps, margin: 'normal', fullWidth: true, };
        const {values} = formProps;
        return (
            <Fragment>
                <form noValidate>
                    <TextField
                        {...fieldProps}
                        required
                        autoFocus
                        value={values.first_name}
                        type="text"
                        name="first_name"

                    />

                    <TextField
                        {...fieldProps}
                        name="last_name"
                        type="text"
                    />

                    <TextField
                        {...fieldProps}
                        required
                        name="email"
                        type="email"
                        value={values.email}

                    />
                </form>
                <Button onClick={this.onClick}>Login</Button>
            </Fragment>
        );
    }}
/>

我正在尝试这个解决方案https://github.com/jaredpalmer/formik/issues/73#issuecomment-317169770但它总是返回给我Uncaught TypeError: _this.props.onSubmit is not a function

当我尝试console.log(this.form)submitForm功能。

大佬们有什么解决办法吗?


- Formik 版本:最新 - React 版本:v16 - 操作系统:Mac OS

解答

只是对于任何想知道通过 React hooks 的解决方案是什么的人:

Formik 2.x,如这个回答中所述

// import this in the related component
import { useFormikContext } from 'formik';

// Then inside the component body
const { submitForm } = useFormikContext();

const handleSubmit = () => {
  submitForm();
}

请记住,该解决方案仅适用于内部 Formik 组件的组件,因为它使用上下文 API。如果由于某种原因您想从外部组件或实际使用 Formik 的组件手动提交,您实际上仍然可以使用innerRef属性。

TLDR ;如果您提交的组件是<Formik>withFormik()组件的子组件,则此上下文答案就像一个魅力,否则,请使用下面的innerRef答案。

Formic 1.5.x+

// Attach this to your <Formik>
const formRef = useRef()

const handleSubmit = () => {
  if (formRef.current) {
    formRef.current.handleSubmit()
  }
}

// Render
<Formik innerRef={formRef} />
Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐