Joy*_*Joy 3 reactjs react-hook-form use-form
我正在使用 React useForm 钩子从表单提交数据。要求是用户在提交之前应该在预览 div 中看到示例数据。如何从输入文本框中获取值并将其显示在输入旁边的 div 中。文档中有 getValue 方法可以使用吗?
<form>
<div class="mb-6">
<label class="block mb-2">Enter Title: </label>
<input type="text" id="page_text" class="text-white" placeholder="Enter Title" {...register('page_Title',{ required: "Enter Your Title", maxLength: {value:255,message:"Cannot Exceed more 255 Characters" } })}/>
</div>
</form>
<div className= "text-white text-center rounded-xl shadow-xl">
<h1>Preview</h1>
<h3>{getValues("page_Title")}</h3>
</div>
Run Code Online (Sandbox Code Playgroud)
我在这里创建了一个沙箱:https://codesandbox.io/s/angry-wave-nef2jo
基本上问题是当您输入文本(onChange)时 getValues 不会自动更新。您需要使用此处文档中所述的 watch 方法:https ://react-hook-form.com/api/useform/watch
例如:
const pageTitle = watch("page_Title", false);
Run Code Online (Sandbox Code Playgroud)
然后:
<h3>{pageTitle}</h3>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14309 次 |
| 最近记录: |