You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用React和Formik时如何在<Form>组件外部触发Formik的onSubmit方法

解决方案

实现思路

你之前直接调用children.props.onSubmit没有生效,是因为这个prop是你直接传给Formik的原始方法,没有经过Formik内部的表单取值、校验逻辑封装,必须调用Formik实例暴露的submitForm方法才能触发完整提交流程,拿到最新表单值和onSubmit的返回结果。

具体实现步骤

  • 在App组件中创建ref,绑定到Formik的innerRef属性上,获取Formik实例
  • 将Formik实例的submitForm方法通过props传递给Parent组件
  • Parent组件中点击按钮时调用传入的submitForm方法即可

修改后的App代码

import { useRef } from 'react';
import {Formik, Form, Field} from 'formik';
import Parent from './Parent'

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

function App() {
  const formikRef = useRef(null);
  return (
    <Parent submitForm={() => formikRef.current?.submitForm()}>
      <Formik
        innerRef={formikRef}
        initialValues={{
          name: 'John',
          age: 27
        }}
        onSubmit={async (values) => {
          console.log('values',values);
          await sleep(2000);
          return 'success'
        }}
      >
        <Form>
          <label htmlFor="name">Name</label>
          <Field
            type="text"
            name="name"
          />
          <label htmlFor="age">Age</label>
          <Field
            type="number"
            name="age"
          />
        </Form>
      </Formik>
    </Parent>
  );
}

export default App;

修改后的Parent代码

const Parent = (props) => {
  const handleSubmit = async () => {
    const res = await props.submitForm()
    if (res) {
      console.log('res', res);
    }
  };

  return (
    <div>
        <h1>Hello</h1>
        {props.children}
        <button type="button" onClick={handleSubmit}>Submit Form</button>
    </div>
  );
}

export default Parent;

注意事项

  • 提交按钮要手动指定type="button",避免触发表单原生提交行为导致页面刷新
  • Formik实例还暴露了validateForm、resetForm等方法,有对应需求可以直接调用

内容的提问来源于stack exchange,提问作者Andy Pandy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 12:33:00