简体   繁体   English

react-hook-form isDirty 对我来说似乎很奇怪

[英]react-hook-form isDirty seems weird for me

Today, I started to use react-hook-form and the isDirty variable seems quite weird for me.今天,我开始使用 react-hook-form 并且isDirty变量对我来说似乎很奇怪。 It is always true although only the focus was given to any input elements.尽管只关注任何输入元素,但它始终是正确的。

I expect isDirty should be true only when value of input element changes.我希望 isDirty 只有当输入元素的值发生变化时才应该为真。 Is that normal in react-hook-form?这在反应钩形式中正常吗?

// 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())
    }
}

UPDATE: I think this is a bug of react-hook-form?更新:我认为这是 react-hook-form 的错误? react-hook-form version 6.11.0 react-hook-form 版本 6.11.0

This happens only when React.forwardRef was used.这仅在使用 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>
    )
})

I had a similar issue and I ended up solving it by checking length of dirtyFields property of the formState.我有一个类似的问题,我最终通过检查formState 的dirtyFields属性的长度来解决它。

In react hook form, you may feel that isDirty behaves more like it is isTouched .在 react hook 形式中,您可能会觉得isDirty 的行为更像是isTouched But you have to pass the defaultValue to the input field because RHF needs a value to compare against as mentioned in the official documents.但是您必须将defaultValue传递给输入字段,因为 RHF 需要一个值进行比较,如官方文档中所述。

在此处输入图片说明

Let me know if that makes sense.让我知道这是否有意义。

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

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