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

Jak*_*eon 4 reactjs react-hook-form

今天,我开始使用react-hook-form,isDirty变量对我来说似乎很奇怪。尽管只有焦点被赋予了任何输入元素,但它始终是正确的。

我期望 isDirty 仅当输入元素的值发生变化时才应该为 true。这在反应钩子形式中正常吗?

// 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())
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:我认为这是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>
    )
})
Run Code Online (Sandbox Code Playgroud)

Kri*_*lye 10

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

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

在此输入图像描述

让我知道这是否有意义。