反应 useForm 从 TextBox 获取值

React useForm get value from TextBox

我正在使用 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>

在表单中放置一个按钮并触发 getValues() 方法。如下图

<button
    type="button"
    onClick={() => {
      const values = getValues(); // { page_title: "someValue", test1: "test1-input", ... }
      console.log({values});
    }}
  >
    Get Values
  </button>

也看看 docs link 中的这个基本示例

我在这里创建了一个沙箱:https://codesandbox.io/s/angry-wave-nef2jo

问题基本上是当您输入文本时 getValues 不会自动更新 (onChange)。您需要使用此处文档中描述的 watch 方法:https://react-hook-form.com/api/useform/watch

例如:

const pageTitle = watch("page_Title", false);

然后:

<h3>{pageTitle}</h3>