使用 react-hook-form 监听(观看)字段的最佳方法

Best approach to listen (watch) a field using react-hook-form

提问人:AndresSp 提问时间:11/13/2023 更新时间:11/13/2023 访问量:40

问:

我想根据选择字段更新页面状态

下面是一个示例:

import React from 'react';
import { useForm, Controller, useWatch } from 'react-hook-form';

const MyForm = () => {
  const { control } = useForm();
  const selectedRoom = watch('room', '');

  // You can perform actions based on the selected room
  React.useEffect(() => {
    // Example: Log the selected room to the console
    console.log('Selected Room:', selectedRoom);

    // Add any other logic you want to execute based on the room field
  }, [selectedRoom]);

  return (
    <form>
      {/* Room Selection */}
      <div>
        <label>Room:</label>
        <Controller
          name="room"
          control={control}
          defaultValue=""
          render={({ field }) => (
            <select {...field}>
              <option value="">Select a room</option>
              <option value="room1">Room 1</option>
              <option value="room2">Room 2</option>
              {/* Add more rooms as needed */}
            </select>
          )}
        />
      </div>

      {/* Start Date */}
      <div>
        <label>Start Date:</label>
        <Controller
          name="startDate"
          control={control}
          defaultValue=""
          render={({ field }) => <input type="date" {...field} />}
        />
      </div>

      {/* End Date */}
      <div>
        <label>End Date:</label>
        <Controller
          name="endDate"
          control={control}
          defaultValue=""
          render={({ field }) => <input type="date" {...field} />}
        />
      </div>

      {/* Button without onSubmit */}
      <button type="button">Simulate Submit</button>
    </form>
  );
};

export default MyForm;

这里的问题是,如果您阅读文档,您可以找到以下内容:

监视结果针对渲染阶段进行了优化,而不是针对 useEffect 的 deps,要检测值更新,您可能需要使用外部自定义 用于价值比较的钩子

https://react-hook-form.com/docs/useform/watch

我可以使用什么?使用手表?选择 onChange? 我避免了onChange,因为我已经使用Controller和useFormContext创建了表单控件 使用 react-hook-form 的想法是从那里注册表单和控件,对吧?

javascript reactjs 反应钩子形式

评论


答: 暂无答案