简体   繁体   English

为 Formik 的 innerRef 获取 null

[英]Get null for innerRef of Formik

When I try to get reference on formik, I get null in current field of ref object.当我尝试在 formik 上获取参考时,我在 ref 对象的当前字段中得到 null。

const formikRef = useRef();
...

  <Formik
    innerRef={formikRef}
    initialValues={{
      title: '',
    }}
    onSubmit={(values) => console.log('submit')}
  >

And next:接下来:

useEffect(() => {

    console.log(formikRef);
  }, []);

Get:得到:

Object {
  "current": Object {
    "current": null,
  },
}

How can I fix this problem?我该如何解决这个问题? Help please.请帮忙。

If you want to call submit function outside Formik, you can use useImperativeHandle .如果你想在 Formik 之外调用提交函数,你可以使用useImperativeHandle Document 文档

// Children Component

const Form = forwardRef((props, ref) => {
  const formik = useFormik({
    initialValues,
    validationSchema,
    onSubmit,
    ...rest // other props
  })

  useImperativeHandle(ref, () => ({
    ...formik
  }))

  return ** Your form here **
})

and using:并使用:

// Parent Component

const Parent = () => {
  const formRef = useRef(null)

  const handleSubmitForm = (values, actions) => { 
    // handle logic submit form
  }

  const onSubmit = () => {
    formRef.current.submitForm()
  }

  return (<>
    <Form ref={formRef} onSubmit={handleSubmitForm} />
    <button type="button" onClick={onSubmit}>Submit</button>
   </>)
}

Read the ref only when it has value, and add the dependency in useEffect on the ref.仅在 ref 有值时才读取 ref,并将 useEffect 中的依赖项添加到 ref 上。

useEffect(() => {
    if (formikRef.current) {
        console.log(formikRef);
    }
  }, [formikRef]);

Remember, that refs handle it's actual value in .current property.请记住,refs 在 .current 属性中处理它的实际值。

What worked for me was adding variables inside useEffect's [].对我有用的是在 useEffect 的 [] 中添加变量。 For my case, it was [ref.current, show] .就我而言,它是[ref.current, show]

Add an if(ref.current) {...} before any ref.current.setFieldValue in useEffect body as well or ref.current?.setFieldValue .useEffect主体中的任何ref.current.setFieldValueref.current?.setFieldValue之前添加一个if(ref.current) {...}

This cost me several hours, I hope you're better off.这花了我几个小时,我希望你过得更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM