reactjs - 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 进行实时验证?如果你能给我一个答案,我将不胜感激。(对不起,尴尬的英语。)
解决方案
推荐阅读
- javascript - 查看在 JavaScript 中设置规则
- sql - 如何使用 powershell sql 检查错误
- javascript - Bootstrap 4 动态 WordPress 轮播不会滑动
- java - java.lang.InstantiationException 尽管存在 NoArgsConstructor
- certificate - 证书说在 Firefox 上被撤销,但在 ssl 证书验证网站上没有
- javascript - 计算具有球员评分的两支相等的球队
- javascript - 无法为我的排序方法创建下拉按钮
- c# - HttpClient 未从 UWP 应用程序连接到 URL
- python - python字典是什么数据结构?
- sql-server - 参数无效 - System.Drawing.Image.FromStream(Ms)