react-hook-form isDirty 对我来说似乎很奇怪
react-hook-form isDirty seems weird for me
今天,我开始使用 react-hook-form,isDirty 变量对我来说似乎很奇怪。
尽管仅将焦点给予任何输入元素,但始终如此。
我希望 isDirty 仅在输入元素的值发生变化时才为真。这在 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())
}
}
更新:我认为这是 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>
)
})
我有一个类似的问题,我最终通过检查 formState 的 dirtyFields 属性 的长度解决了这个问题。
在 React 钩子形式中,您可能会觉得 isDirty 的行为更像是 isTouched。但是你必须将 defaultValue 传递给输入字段,因为 RHF 需要一个值来与官方文档中提到的进行比较。
让我知道这是否有意义。
今天,我开始使用 react-hook-form,isDirty 变量对我来说似乎很奇怪。 尽管仅将焦点给予任何输入元素,但始终如此。
我希望 isDirty 仅在输入元素的值发生变化时才为真。这在 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())
}
}
更新:我认为这是 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>
)
})
我有一个类似的问题,我最终通过检查 formState 的 dirtyFields 属性 的长度解决了这个问题。
在 React 钩子形式中,您可能会觉得 isDirty 的行为更像是 isTouched。但是你必须将 defaultValue 传递给输入字段,因为 RHF 需要一个值来与官方文档中提到的进行比较。
让我知道这是否有意义。