首页 > 解决方案 > 为自定义输入字段实现一个清除按钮,以使用反应挂钩表单触发所需的错误

问题描述

期待

当我们用十字按钮清除输入字段时,React Hook 表单应该显示错误消息

问题

  1. 使用十字按钮清除值后未显示所需的错误消息。
  2. 使用十字按钮清除值后,提交按钮未被禁用。

自定义输入字段的代码

import React, { useRef } from 'react';

export default function MyInput(props) {
  const inputRef = useRef();

  const clear = () => {
    if (inputRef.current) {
      inputRef.current.value = '';
    }
  }

  return (
    <>
      <input ref={inputRef} {...props} />
      {/* I want to trigger the required error of react hook form on clear*/}
      <button onClick={clear} style={{
        marginLeft: '-1.2rem',
        cursor: 'pointer'
      }}>x</button>
    </>
  );
}

表格中的用法

          <Controller
            name="firstName"
            control={control}
            rules={{
              required: {
                value: true,
                message: 'You must enter your first name'
              }
            }}
            render={({ field: { ref, ...rest } }) => <CustomInput {...rest} />}
          />

不确定是否useRef是正确的方法,但我想使用一个不受控制的输入,我想用一个清除按钮自定义

链接到 Stackblitz -带有清除按钮的自定义输入

标签: reactjsreact-hook-form

解决方案


让表单知道单击清除按钮时更改的setValue一种方法是从useForm钩子中调用该方法以手动注册更改。

因此,我可以将 setValue 作为道具传递给我的子组件,即自定义输入,并在输入字段的清除按钮的单击事件上设置新值

  const clear = () => {
    setValue(name, '', { 
      shouldValidate: true, 
      shouldDirty: true 
    });
  }

useRef用例也不需要。

链接到更新的 Stackblitz -带有清除按钮的自定义输入


推荐阅读