当前行为
(this.form = node)}
onSubmitCallback={this.onSubmitCallback}
render={formProps => {
const fieldProps = { formProps, margin: 'normal', fullWidth: true, };
const {values} = formProps;
return (
Login
);
}}
/>我正在尝试这个解决方案
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 - OS: Mac
发布于 2019-10-04 00:58:53
对于那些想知道通过React钩子有什么解决方案的人来说:
Formik 2.x,如中所述这个答案
// import this in the related component
import { useFormikContext } from 'formik';
// Then inside the component body
const { submitForm } = useFormikContext();
const handleSubmit = () => {
submitForm();
}请记住,解决方案仅适用于组件内部
Formik组件,因为它使用上下文API。如果出于某种原因,您希望从外部组件或从实际使用Formik的组件手动提交,则实际上仍然可以使用innerRef道具。
TLDR;如果您要提交的组件是或的子级,则此上下文answers的作用就像是一个咒语withFormik()组件,否则使用innerRef请回答下面的问题。
Formik 1.5.x+
// Attach this to your
const formRef = useRef()
const handleSubmit = () => {
if (formRef.current) {
formRef.current.handleSubmit()
}
}
// Render发布于 2018-11-20 07:05:28
你可以绑定formikProps.submitForm(Formik的程序性提交)到父组件,然后触发来自父组件的提交:
import React from 'react';
import { Formik } from 'formik';
class MyForm extends React.Component {
render() {
const { bindSubmitForm } = this.props;
return (
{
console.log({ values });
setSubmitting(false);
}}
>
{(formikProps) => {
const { values, handleChange, handleBlur, handleSubmit } = formikProps;
// bind the submission handler remotely
bindSubmitForm(formikProps.submitForm);
return (
)
}}
)
}
}
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 (
Submit from outside
)
}
}
export default MyApp;发布于 2020-12-28 21:43:13
我找到的最好的解决方案在这里描述https://stackoverflow.com/a/53573760
将答案复制到此处:
在表单中添加"id“属性: id='my-form‘
class CustomForm extends Component {
render() {
return (
// Form Inputs go here
);
}
}然后将相同的Id添加到表单外部的目标按钮的"form“属性中:
Outside Button现在,“外部按钮”按钮将完全等效,就好像它在表单内部一样。
注意: IE11不支持此功能。
https://stackoverflow.com/questions/49525057
复制相似问题