javascript - 对象可能为“空”: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
toformRef!.current.isValid
和formRef.current.dirty
toformRef!.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
推荐阅读
- pytorch - 张量板不一致的折线图颜色
- swift - Swift Combine - 如何抛出错误并停止执行
- r - ggstatsplot::ggbetweenstats: 显示真实的 p 值
- debugging - 如何在没有客户提供的任何可执行文件的情况下调试核心文件
- database - SpringBoot中数据实体的异常类:全局异常类还是每个实体单独的异常类?
- django - 授权和获取访问令牌后如何将用户传回前端客户端?
- swift - Swift 5 中的日期格式
- python - 在 Python 中为指数值获取不正确的最大值和最小值
- maven - 由于我工作的网络,我无法创建 Spring Boot 项目
- javascript - 有没有办法在不使用画布的情况下实现图像颜色选择 javascript?