[英]Object is possibly 'null': TypeScript, React useRef & Formik innerRef
在我使用 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 | )
嘗試將formRef.current.isValid
更改為formRef..current.isValid
並將formRef.current.dirty
為formRef..current.dirty
但錯誤仍然存在。
為什么會這樣,我們如何解決這個錯誤? 謝謝!
import React, { useState, useEffect, useRef } from 'react';
import { Button, Modal, Form } from 'react-bootstrap';
import { Formik } from 'formik';
interface IModal {
show: boolean;
handleClose: () => void;
}
export function NicknameModal({show, handleClose}: IModal) {
const formRef = useRef(null);
return (
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>My Title</Modal.Title>
</Modal.Header>
<Modal.Body>
<Formik
initialValues={{
nickname: '',
}}
innerRef={formRef}
onSubmit={(
values,
{ setSubmitting }
) => {
setSubmitting(true);
handleClose();
setSubmitting(false);
}}
>
{({values, errors, touched, handleChange, handleBlur, handleSubmit, isSubmitting, setFieldValue }) => (
<Form id="nicknameForm" onSubmit={handleSubmit}>
<Form.Group controlId="formNickname">
<Form.Label>Nickname</Form.Label>
<Form.Control type="text" name="nickname" onChange={handleChange} onBlur={handleBlur} value={values.nickname} />
</Form.Group>
</Form>
)}
</Formik>
</Modal.Body>
<Modal.Footer>
<Button variant="primary" type="submit"
disabled={!(formRef.current.isValid && formRef.current.dirty)}
form="nicknameForm">Apply</Button>
</Modal.Footer>
</Modal>
)
}
更新:
如果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>
您需要為 useRef 設置類型,其中 FormValues 是您的表單值
type FormValues = {};
useRef<FormikProps<FormValues>>(null);
https://github.com/formium/formik/issues/2600#issuecomment-693479057
嘗試:
import { FormikProps } from "formik";
const formRef = useRef<FormikProps<any>>(null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.