问题
Some info
I am using Formik for my project and I have my setup looking like this:
|-MenuModal
|--MenuEdit
|---MenuEditForm
Where MenuModal
is the parent to MenuEdit
and MenuEditForm
. The component MenuEditForm
is responsible for returning the Formik form, but I am calling the submit in it's parent MenuModal
, which laters runs the submit function in MenuEdit
via React's refs. Messy? Yup!
My problem
Right now I am trying to use state and callback functions to get the Formiks values
from MenuEditForm
to MenuEdit
. But since I am not using Formiks own onSubmit
:
<Formik
initialValues={menu}
validationSchema={validationSchema}
onSubmit={values => console.log('values', values)} // 'values' is undefined
...
My values
will be undefined and I can't make my submit function go through.
So I wonder how I can access my values
in MenuEditForm
so I later can pass it up to MenuEdit
and complete my submit function.
Thanks for reading.
回答1:
To access values outside of the formik component, you can do this with hooks:
const formRef = useRef();
return (
<Formik
...
innerRef={formRef}
>
...
</Formik>
Then, can access values using formRef.current.values anywhere outside of the component.
回答2:
You can simply pass a function to receive the values from child component.
Eg:
MenuModal:
const MenuModal = () => {
const [values, setvalues] = useState();
return (
...
<MenuEdit values={values} onFormSubmit={(values) => setvalues(values)} />
...
);
}
MenuEdit:
const MenuEdit = ({values, onFormSubmit}) => {
// do something with values
return (
...
<MenuEditForm onFormSubmit={onFormSubmit} />
...
)
...
}
MenuEditForm:
const MenuEditForm = ({onFormSubmit}) => (
...
<Formik
initialValues={menu}
validationSchema={validationSchema}
onSubmit={values => onFormSubmit(values)}
...
)
来源:https://stackoverflow.com/questions/51364080/access-formiks-values-outside-of-component-react