React Formik中‘handleSubmit未定义’错误:定义与调用疑问
问题解决:'handleSubmit'未定义的修复方案
问题根源
你现在把handleSubmit当成组件的入参了,但实际上这个方法是Formik实例生成的,不需要从外部传入,而且你的组件参数写法本身就有问题(没有用对象解构,直接罗列参数会导致所有值都是undefined)。
正确的定义与调用步骤
修正组件参数
你的MyForm组件不需要接收这些零散的参数,Formik会内部生成handleSubmit、handleChange等方法,所以组件定义应该简化:const MyForm = () => { // 内部逻辑写在这里 }从Formik实例解构所需方法
创建formik实例后,直接从里面解构出你需要的方法和状态:const MyForm = () => { const formik = useFormik({ initialValues: { NameoftheUPSIProject: '', InformationSharedBy: '', InfoSharedwithrespectto: '', InsiderTypes: '', ContactPerson: '', NameoftheOrganization: '', DateofSharing: '', ParticularofInformationShared: '', PurposeofSharing: '', ModeofSharing: '', }, validationSchema: formValidation, onSubmit: (values) => { // 确保apple函数已经定义,这里是表单提交后的逻辑 apple(values); }, }); // 解构Formik生成的方法和状态 const { handleSubmit, handleChange, handleBlur, values, touched, errors } = formik; }在表单中调用handleSubmit
给你的<form>标签绑定onSubmit事件,使用解构出来的handleSubmit:return ( <form onSubmit={handleSubmit}> {/* 表单输入框示例,绑定对应的Formik方法 */} <input name="NameoftheUPSIProject" value={values.NameoftheUPSIProject} onChange={handleChange} onBlur={handleBlur} /> {/* 其他表单字段同理 */} <button type="submit">提交</button> </form> );
完整修正后的代码
import { useFormik } from 'formik'; // 确保formValidation已经正确导入 const MyForm = () => { const formik = useFormik({ initialValues: { NameoftheUPSIProject: '', InformationSharedBy: '', InfoSharedwithrespectto: '', InsiderTypes: '', ContactPerson: '', NameoftheOrganization: '', DateofSharing: '', ParticularofInformationShared: '', PurposeofSharing: '', ModeofSharing: '', }, validationSchema: formValidation, onSubmit: (values) => { // 替换为你的实际提交逻辑,确保apple函数已定义 apple(values); }, }); const { handleSubmit, handleChange, handleBlur, values, touched, errors } = formik; return ( <form onSubmit={handleSubmit}> {/* 示例输入框,其他字段依此类推 */} <div> <label>UPSI项目名称</label> <input name="NameoftheUPSIProject" value={values.NameoftheUPSIProject} onChange={handleChange} onBlur={handleBlur} /> {touched.NameoftheUPSIProject && errors.NameoftheUPSIProject && ( <span>{errors.NameoftheUPSIProject}</span> )} </div> {/* 其他表单字段 */} <button type="submit">提交表单</button> </form> ); }; export default MyForm;
调用组件
在需要使用表单的地方直接导入并渲染即可:
import MyForm from './MyForm'; const App = () => { return ( <div> <h1>UPSI信息共享表单</h1> <MyForm /> </div> ); };
内容的提问来源于stack exchange,提问作者arasu ramanan
相关产品推荐
相关产品推荐

