首页 > 解决方案 > react-hook-form 控制器值未提交

问题描述

我正在使用 react-hook-form v6(6.13.1)。我使用 a 是因为我必须实时验证这些值。

/* eslint-disable eqeqeq */
import React, { useEffect, useState } from "react";
import { Controller } from "react-hook-form";

function InputMasking({ label, value, name, control }) {
  const [maskValue, setMaskValue] = useState("");

  const maskingChange = (e) => {
    setMaskValue(e.target.value);
  };

  // validate from value real time
  useEffect(() => {
    if (name == "ipAddr") {
      setMaskValue(maskValue.replace(/[^0-9.]/g, ""));
    }

    if (name == "macAddr") {
      setMaskValue(maskValue.replace(/([^0-9A-Fa-f:])/g, ""));
    }
  }, [name, value, maskValue]);

  return (
    <div>
      <label>{label}</label>
      <>
        <Controller
          name={name}
          control={control}
          defaultValue={value ? value : maskValue}
          render={
            () => (
              <input name={name} value={maskValue} onChange={maskingChange} />
            )
            // value ? (
            //   <input name={name} key={value} defaultValue={value} />
            // ) : (
            //   <input name={name} value={maskValue} onChange={maskingChange} />
            // )
          }
        />
      </>
    </div>
  );
}

export default InputMasking;

应用程序.js

import { Controller, useForm } from "react-hook-form"; 
import InputMasking from "./InputMasking";
import "./styles.css";

export default function App() {
  const { handleSubmit, control } = useForm();
  return (
    <div className="App">
      <form onSubmit={handleSubmit((data) => console.log(data))}>
        {/* This component is return "" */}
        <InputMasking
          label="Controller render"
          name="macAddr"
          control={control}
        />
        <button type="submit">submit</button>
      </form>
    </div>
  );
}

该组件未提交。默认值通常返回,但此后输入的值未传输。所以我使用了 as() 方法而不是 render() 方法,但是这个方法无效。
您可以在此处查看 condesandbox:https
://codesandbox.io/s/vigorous-kowalevski-850ko 如何使用 react-hook-form 进行实时验证?如果你能给我一个答案,我将不胜感激。(对不起,尴尬的英语。)

标签: reactjsreact-hook-form

解决方案


推荐阅读