首页 > 解决方案 > react-hook-form isDirty 对我来说似乎很奇怪

问题描述

今天,我开始使用 react-hook-form 并且isDirty变量对我来说似乎很奇怪。尽管仅将焦点放在任何输入元素上,但它始终是正确的。

我希望 isDirty 只有在输入元素的值发生变化时才应该为真。这在反应钩子形式中是正常的吗?

// I had to make workaround like this. but I am not sure if this is normal for everybody.
const closeForm = () => {
    const { dirtyFields } = form.formState
    const isReallyDirty = Object.keys(dirtyFields).length > 0

    if (isReallyDirty) {
        if (window.confirm("Discard the changes?")) {
            dispatch(closeItem())
        }
    } else {
        dispatch(closeItem())
    }
}

更新:我认为这是 react-hook-form 的错误? react-hook-form 版本 6.11.0

这仅在使用 React.forwardRef 时发生。

const TextareaBox = ({ ref, ...props }) => {
    const { errors, name } = props
    const { required, ...restProps } = props

    return (
        <Row>
            <Label {...props} columnSize={2} />
            <Col lg={10}>
                <textarea id={name} {...restProps} maxLength="200" rows="3" ref={ref} />
                <ErrorMessage className="errorMessage" errors={errors} name={name} as="p" />
            </Col>
        </Row>
    )
}

const TextareaBox = React.forwardRef((props, ref) => {
    const { errors, name } = props
    const { required, ...restProps } = props

    return (
        <Row>
            <Label {...props} columnSize={2} />
            <Col lg={10}>
                <textarea id={name} {...restProps} maxLength="200" rows="3" ref={ref} />
                <ErrorMessage className="errorMessage" errors={errors} name={name} as="p" />
            </Col>
        </Row>
    )
})

标签: reactjsreact-hook-form

解决方案


我有一个类似的问题,我最终通过检查 formState 的dirtyFields属性的长度来解决它。

在 react hook 形式中,你可能会觉得isDirty 的行为更像isTouched。但是您必须将defaultValue传递给输入字段,因为 RHF 需要一个值来进行比较,如官方文档中所述。

在此处输入图像描述

让我知道这是否有意义。


推荐阅读