Привет всем. Подскажите пожалуйста как можно отправлять форму (Formik) из родительского компонента. До 2й версии Formik я это делал с помощью `ref`. А в новых версиях получаю ошибку `Warning: Function components cannot be given refs`. Выложил код и в
CodeSandbox.
App.js
import React, { Component, createRef } from "react";
import ReactDOM from "react-dom";
import FormCustomer from "./FormCustomer";
import { Button } from "reactstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import "./styles.css";
class App extends Component {
formRef = createRef();
onSubmit = () => {
const form = this.formRef.current;
form.submitForm().then(() => {
console.log(JSON.stringify(form.state.values, null, 2));
});
};
render() {
return (
<div className="App container">
<FormCustomer formRef={this.formRef} />
<Button color="primary" onClick={this.onSubmit}>
Отправить
</Button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Form.js
import React from "react";
import { FormGroup, Label } from "reactstrap";
import { Formik, Form, Field } from "formik";
import * as Yup from "yup";
const formValidationSchema = Yup.object().shape({
docSerial: Yup.string().required(),
docNumber: Yup.string().required()
});
const initialValues = {
docSerial: "4323",
docNumber: "234234"
};
const FormCustomer = ({ formRef }) => {
return (
<Formik
ref={formRef}
initialValues={initialValues}
validationSchema={formValidationSchema}
onSubmit={() => {}}
>
{({ errors, touched, handleSubmit }) => (
<Form onSubmit={handleSubmit}>
<FormGroup className="has-top-label">
<Label>Серия</Label>
<Field
className="form-control"
name="docSerial"
autoComplete="off"
/>
{errors.docSerial && touched.docSerial ? (
<div className="invalid-feedback d-block">{errors.docSerial}</div>
) : null}
</FormGroup>
<FormGroup className="has-top-label">
<Label>Номер</Label>
<Field
className="form-control"
name="docNumber"
autoComplete="off"
/>
{errors.docNumber && touched.docNumber ? (
<div className="invalid-feedback d-block">{errors.docNumber}</div>
) : null}
</FormGroup>
</Form>
)}
</Formik>
);
};
export default FormCustomer;