我使用Formik在React中编写了以下表单:
import React, { FunctionComponent } from 'react';
import { NavLink } from 'react-router-dom';
import { object, string } from 'yup';
import { Formik, FormikActions, Field, FormikProps } from 'formik';
import SimpleInput from './Fields/SimpleInput';
import FieldError from './Fields/FieldError';
interface FormValues {
email: string;
password: string;
}
interface OwnProps {
onSubmit: (data: FormValues) => any;
}
const validationSchema = object().shape({
email: string()
.email('Please enter a valid email address')
.required('Email is a required field'),
password: string()
.min(8)
.required('Password is a required field'),
});
type Props = OwnProps;
const LoginForm: FunctionComponent<Props> = ({ onSubmit }) => {
const initialValues = {
email: '',
password: '',
};
const onFormSubmit = async (values: FormValues, { setSubmitting }: FormikActions<FormValues>) => {
await onSubmit(values);
setSubmitting(false);
};
return (
<Formik
onSubmit={onFormSubmit}
initialValues={initialValues}
validationSchema={validationSchema}
render={({ handleSubmit, isSubmitting }: FormikProps<FormValues>) => (
<form className="ipx-form sign" onSubmit={handleSubmit}>
<h1>Sign in</h1>
<div className="ipx-register-here">
( Don't have an account? )
<NavLink to="/register">Register here</NavLink>
</div>
<br />
<Field name="email" type="email" component={SimpleInput} label="Email Address" placeholder="Email" />
<FieldError name="email" />
<br />
<br />
<div className="fields">
<Field name="password" type="password" component={SimpleInput} label="Password" placeholder="Password" />
<FieldError name="password" />
</div>
<br />
Forgot <NavLink to="/forgot-password">password?</NavLink>
<br />
<button className="button ipx-submit-button" id="ipx-login-submit" type="submit" disabled={isSubmitting}>
<span className="ladda-label">Sign in</span>
</button>
</form>
)}
/>
);
};
export default LoginForm;
如果我点击按钮提交表单(它会发送Redux操作并记录用户登录),那么一切都很正常,但是当我尝试使用Return / Enter键提交表单时,它无法捕获事件。我尝试在
<form>
元素的 onSubmit
属性中记录事件,但是根本没有触发任何按 Enter 键的事件。这个相同的表单之前使用 redux-form
编写,Return 键功能正常。起初我认为可能是异步表单处理引起的问题,但是我切换到了常规同步函数,也不起作用。
有人遇到类似的问题吗?如果是,请分享任何修复方法。
谢谢! Codesandbox
onSubmit
属性中记录事件,但当我按下回车键时它根本不记录任何内容。 - Andrej Naumovski