从另一个组件中读取react-hook-form中的值,可以通过以下步骤实现:
import { useFormContext } from 'react-hook-form';
const { register, handleSubmit, errors, watch } = useFormContext();
const fieldValue = watch('fieldName');
其中,'fieldName'是需要读取值的表单字段的名称。
下面是一个完整的示例代码:
import React from 'react';
import { useFormContext } from 'react-hook-form';
const AnotherComponent = () => {
const { watch } = useFormContext();
const fieldValue = watch('fieldName');
return (
<div>
<p>另一个组件中读取到的值为:{fieldValue}</p>
</div>
);
};
export default AnotherComponent;
在上述示例中,我们通过useFormContext()函数获取了react-hook-form的上下文,并使用watch()函数监听了名为'fieldName'的表单字段的变化,并将其值展示在另一个组件中。
这种方法可以在不同组件之间共享表单数据,并实时获取最新的值。
TVP技术夜未眠
《民航智见》线上会议
腾讯技术开放日
“中小企业”在线学堂
云+社区技术沙龙[第7期]
云+社区技术沙龙[第11期]
云+社区技术沙龙[第14期]
云+社区沙龙online [腾讯云中间件]
“WeCity未来城市”
领取专属 10元无门槛券
手把手带您无忧上云