标签: use-form

React useForm 从 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>
Run Code Online (Sandbox Code Playgroud)

reactjs react-hook-form use-form

3
推荐指数
1
解决办法
1万
查看次数

反应测试库,尝试测试 useForm 验证消息

我正在尝试为表单上的验证编写 RTL 测试。我正在使用useFormhook 来Yup进行验证。

我想测试的场景是当用户单击Add提交的按钮而不填写所有必填字段(标题和描述)时。在这种情况下,一些错误消息将在 from 的空输入下弹出。我想测试的正是这些消息。

我已经编写了测试,在其中找到标题、描述和“添加”按钮,但是当我单击“添加”按钮并执行操作时,screen.debug()错误消息不存在。

表单输入被截断:

  <div className="Form__title">
    <label className="Form__title--label" htmlFor="title">
      Title
    </label>
    <input
      {...register("title")}
      type="text"
      placeholder="Title..."
      data-testid="titleInput"
    />
    {errors?.title && (
      <p data-testid="titleError">{errors.title.message}</p>
    )}
  </div>
Run Code Online (Sandbox Code Playgroud)

我的测试:

test("throws title must be at least 1 characters", async () => {
  renderWithProviders(<TileForm />);

  const error = "title must be at least 1 characters";

  const addNewIdeaButton = screen.getByText("Add New Idea");
  await userEvent.click(addNewIdeaButton);
  const descriptionInput = screen.getByTestId("descriptionInput");
  await userEvent.type(descriptionInput, "foo");
  const addButton = …
Run Code Online (Sandbox Code Playgroud)

reactjs react-testing-library use-form

1
推荐指数
1
解决办法
1938
查看次数