如何使用 react-hook-form 的 register 和 react-jhipster 的 ValidatedInput
How to use register of react-hook-form with ValidatedInput of react-jhipster
我有一个包含许多子表单的特殊表单,因此我无法在 react-jhipster
中使用 ValidatedForm
。不过,我还是想用`ValidatedInput.
我有一个功能组件包含:
<ValidatedInput
label={translate('studySpaceApp.question.noiDung')}
id={`question_noiDung_${defaultValues.id}`}
data-cy="noidung"
type="text"
{...register('noiDung')}
onChange={onChangeQuestionContent}
validate={{
required: true,
minLength: { value: 6, message: translate('entity.validation.minlength', { min: 6 }) },
maxLength: { value: 255, message: translate('entity.validation.maxlength', { max: 255 }) },
}}
defaultValue={questionContent}
/>
但是反应警告:函数组件不能被赋予引用。尝试访问此 ref 将失败。您是要使用 React.forwardRef() 吗?
如何解决?
请帮忙!!!
如果要将 ref 传递给功能组件,它们不能直接使用,需要像这样 forwardRef
。
const ValidatedInput = React.forwardRef((props, ref) => (
// Your ValidatedInput body
));
然后 <ValidatedInput ref={yourref} {...otherprops} />
就可以了。
我找到了解决方案,是的...
我试图阅读 react-jhipster
的源代码,我看到他们使用了一个名为 register
的道具,我可以通过我的 register
(const { register } = useForm()
)。然后,这个组件处理其他一切
我有一个包含许多子表单的特殊表单,因此我无法在 react-jhipster
中使用 ValidatedForm
。不过,我还是想用`ValidatedInput.
我有一个功能组件包含:
<ValidatedInput
label={translate('studySpaceApp.question.noiDung')}
id={`question_noiDung_${defaultValues.id}`}
data-cy="noidung"
type="text"
{...register('noiDung')}
onChange={onChangeQuestionContent}
validate={{
required: true,
minLength: { value: 6, message: translate('entity.validation.minlength', { min: 6 }) },
maxLength: { value: 255, message: translate('entity.validation.maxlength', { max: 255 }) },
}}
defaultValue={questionContent}
/>
但是反应警告:函数组件不能被赋予引用。尝试访问此 ref 将失败。您是要使用 React.forwardRef() 吗?
如何解决? 请帮忙!!!
如果要将 ref 传递给功能组件,它们不能直接使用,需要像这样 forwardRef
。
const ValidatedInput = React.forwardRef((props, ref) => (
// Your ValidatedInput body
));
然后 <ValidatedInput ref={yourref} {...otherprops} />
就可以了。
我找到了解决方案,是的...
我试图阅读 react-jhipster
的源代码,我看到他们使用了一个名为 register
的道具,我可以通过我的 register
(const { register } = useForm()
)。然后,这个组件处理其他一切