我正在尝试从使用Formik构造的表单中提取值,但是似乎无法通过onSubmit调用从Formik中获取这些表单值。释放他并在父组件上处理它的最佳方法是什么?
这是表单组件
import React from 'react';
import { Formik, Form, Field } from 'formik';
import * as Yup from 'yup';
import moment from 'moment';
import Header from './Header';
moment.locale('en-gb');
const JoinForm = (props) => {
const initialValues = {
firstName: props.firstName || 'test'
};
return (
<div>
<Formik
initialValues={initialValues}
onSubmit={props.onSubmit}
// onSubmit={(values, actions) => {
// //console.log('this is direct from form',values)
// actions.setSubmitting(false);
// return values;
// }}
>
{props => {
const {
values,
touched,
isSubmitting,
handleChange,
handleSubmit,
handleReset,
handleBlur
} = props;
return (
<Form>
<label>First Name </label>
<Field
type="text"
name="firstName"
placeholder="First Name"
values={values.firstName}
onChange={handleChange}
onBlur={handleBlur}
/>
<button
type="button"
type="submit"
disabled={!!isSubmitting}
>
Submit
</button>
</Form>
);
}}
</Formik>
</div>
);
};
export default JoinForm;
这是父组件
import JoinForm from './JoinForm';
import React from 'react';
import Header from './Header';
import { startAddAthlete } from '../actions/form';
class JoinPage extends React.Component{
onSubmit = (athlete) => {
console.log(athlete);
};
render() {
return (
<div>
<Header />
<JoinForm firstName={'King'} onSubmit={this.onSubmit} />
</div>
);
}
}
export default JoinPage
我这样做正确吗?目的是让父母处理提交内容,并且表单应该可以重新用于编辑等。
答案 0 :(得分:1)
我认为,您的按钮导致了此问题。您已经在按钮上添加了type="button"
和type="submit"
。删除type="button"
应该可以解决此问题。
<button type="submit"
disabled={!!isSubmitting}>
Submit
</button>
希望这会有所帮助。