React使用Formik开发登录表单提交返回空初始对象问题咨询
问题原因
- 你使用的Semantic UI
Input组件未和Formik的状态管理逻辑绑定,Formik无法感知输入框的内容变化,提交时只能读取到初始的空值。 - 你在Formik的render props中只解构了
handleSubmit和isSubmitting,缺少必要的handleChange、values等状态/方法,没有传递给输入组件。
解决方法
方案1:手动绑定属性到Semantic UI Input
在render props中补充解构需要的方法,给每个Input组件绑定name、value、onChange属性即可:
import { Formik, Form } from 'formik'; import { observer } from 'mobx-react'; import React from 'react'; import { Input , Button } from 'semantic-ui-react'; import { useStore } from '../application/stores/store'; export default observer(function LoginForm() { const {userStore} = useStore(); return ( <Formik initialValues={{user:'', password:''}} onSubmit={(values) => { console.log(JSON.stringify(values, null, 2)); userStore.login(values) }} > {/* 补充解构handleChange和values */} {({handleSubmit, isSubmitting, handleChange, values})=> ( <Form className='ui form' onSubmit={handleSubmit} autoComplete='off'> <Input name='user' placeholder='User' value={values.user} onChange={handleChange} /> <Input name='password' placeholder='Password' type='password' value={values.password} onChange={handleChange} /> <Button loading={isSubmitting} positive content ='Login' type='submit' fluid/> </Form> )} </Formik> ) })
方案2:使用Formik的Field组件适配(写法更简洁)
Formik内置的Field组件会自动绑定状态和事件,只需指定as参数为Semantic UI的Input即可:
// 先导入Field组件 import { Formik, Form, Field } from 'formik'; import { observer } from 'mobx-react'; import React from 'react'; import { Input , Button } from 'semantic-ui-react'; import { useStore } from '../application/stores/store'; export default observer(function LoginForm() { const {userStore} = useStore(); return ( <Formik initialValues={{user:'', password:''}} onSubmit={(values) => { console.log(JSON.stringify(values, null, 2)); userStore.login(values) }} > {({handleSubmit, isSubmitting})=> ( <Form className='ui form' onSubmit={handleSubmit} autoComplete='off'> <Field as={Input} name='user' placeholder='User' /> <Field as={Input} name='password' placeholder='Password' type='password' /> <Button loading={isSubmitting} positive content ='Login' type='submit' fluid/> </Form> )} </Formik> ) })
内容的提问来源于stack exchange,提问作者יוני ארליך
相关产品推荐
相关产品推荐

