当前行为
<Formik
isInitialValid
initialValues={{ first_name: 'Test', email: '[email protected]' }}
validate={validate}
ref={node => (this.form = node)}
onSubmitCallback={this.onSubmitCallback}
render={formProps => {
const fieldProps = { formProps, margin: 'normal', fullWidth: true, };
const {values} = formProps;
return (
<Fragment>
<form noValidate>
<TextField
{...fieldProps}
required
autoFocus
value={values.first_name}
type="text"
name="first_name"
/>
<TextField
{...fieldProps}
name="last_name"
type="text"
/>
<TextField
{...fieldProps}
required
name="email"
type="email"
value={values.email}
/>
</form>
<Button onClick={this.onClick}>Login</Button>
</Fragment>
);
}}
/>
我正在尝试此解决方案https://github.com/jaredpalmer/formik/issues/73#issuecomment-317169770,但它总是返回我
Uncaught TypeError: _this.props.onSubmit is not a function
当我尝试
console.log(this.form)
时,有submitForm
函数。有解决方案的人吗?
-Formik版本:最新
-React版本:v16
-作业系统:Mac OS
最佳答案
您可以将formikProps.submitForm
(以编程方式提交)以绑定到父组件,然后触发父组件的提交:
import React from 'react';
import { Formik } from 'formik';
class MyForm extends React.Component {
render() {
const { bindSubmitForm } = this.props;
return (
<Formik
initialValues={{ a: '' }}
onSubmit={(values, { setSubmitting }) => {
console.log({ values });
setSubmitting(false);
}}
>
{(formikProps) => {
const { values, handleChange, handleBlur, handleSubmit } = formikProps;
// bind the submission handler remotely
bindSubmitForm(formikProps.submitForm);
return (
<form noValidate onSubmit={handleSubmit}>
<input type="text" name="a" value={values.a} onChange={handleChange} onBlur={handleBlur} />
</form>
)
}}
</Formik>
)
}
}
class MyApp extends React.Component {
// will hold access to formikProps.submitForm, to trigger form submission outside of the form
submitMyForm = null;
handleSubmitMyForm = (e) => {
if (this.submitMyForm) {
this.submitMyForm(e);
}
};
bindSubmitForm = (submitForm) => {
this.submitMyForm = submitForm;
};
render() {
return (
<div>
<button onClick={this.handleSubmitMyForm}>Submit from outside</button>
<MyForm bindSubmitForm={this.bindSubmitForm} />
</div>
)
}
}
export default MyApp;
关于reactjs - React Formik在<Formik/>之外使用SubmitForm,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49525057/