对象可能为“null”:TypeScript、React useRef 和 Formik innerRef

Nyx*_*nyx 6 javascript typescript reactjs formik react-hooks

在我使用 Formik 的 React/TypeScript 应用程序中,我收到错误

Object is possibly 'null'.  TS2531

    125 |             <Modal.Footer>
  > 126 |                 <Button variant="primary" type="submit" form="nicknameForm" disabled={!(formRef.current.isValid && formRef.current.dirty)}>Apply</Button>
        |                                                                                            ^
    127 |             </Modal.Footer>
    128 |         </Modal>
    129 |     )
Run Code Online (Sandbox Code Playgroud)

尝试更改formRef.current.isValidformRef!.current.isValidformRef.current.dirtyformRef!.current.dirty但错误仍然存​​在。

为什么会这样,我们该如何修复这个错误?谢谢你!

Object is possibly 'null'.  TS2531

    125 |             <Modal.Footer>
  > 126 |                 <Button variant="primary" type="submit" form="nicknameForm" disabled={!(formRef.current.isValid && formRef.current.dirty)}>Apply</Button>
        |                                                                                            ^
    127 |             </Modal.Footer>
    128 |         </Modal>
    129 |     )
Run Code Online (Sandbox Code Playgroud)

更新:

如果const formRef = useRef(null);更改为const formRef = useRef();,我们现在会遇到不同的错误:

Type 'MutableRefObject<undefined>' is not assignable to type '((instance: FormikProps<{ nickname: string; }> | null) => void) & MutableRefObject<undefined>'.
  Type 'MutableRefObject<undefined>' is not assignable to type '(instance: FormikProps<{ nickname: string; }> | null) => void'.
    Type 'MutableRefObject<undefined>' provides no match for the signature '(instance: FormikProps<{ nickname: string; }> | null): void'.  TS2322

    71 |                         nickName: '',
    72 |                     }}
  > 73 |                     innerRef={formRef}
       |                     ^
    74 |                     onSubmit={(
    75 |                         values: Values,
    76 |                         { setSubmitting }: FormikHelpers<Values>

Run Code Online (Sandbox Code Playgroud)

小智 15

您需要设置 useRef 的类型,其中 FormValues 是您的表单值

type FormValues = {};
useRef<FormikProps<FormValues>>(null);
Run Code Online (Sandbox Code Playgroud)

https://github.com/formium/formik/issues/2600#issuecomment-693479057