Access Formik's values outside of component | React

孤人 提交于 2020-08-24 10:44:14

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!