reactjs - 如何通过在 react 中使用 react-hook-form 来获取 react-phone-input-2 值
问题描述
我在提交时获得 TextField 值,但不是 ReactPhoneInput 值,如何使用 react-hook-form 获取值
import ReactPhoneInput from "react-phone-input-2"
import {TextField,Button}from "@material-ui/core"
const {register, handleSubmit,formState: { errors }} = useForm()
const getData= (data) => {
console.log(data.username)
console.log(data.username);
}
形式
<form onSubmit={handleSubmit(getData)} >
<TextField {...register("username")} />
<ReactPhoneInput
inputExtraProps={{
name: "phone",
required: true,
autoFocus: true
}}
country={"in"}
onlyCountries={["in"]}
countryCodeEditable={false}
specialLabel={"Player Mobile Number"}
rules={{ required: true }}
/>
<Button type='submit>Submit</Button>
</form>
解决方案
<ReactPhoneInput />
是一个外部控制组件,因此您应该<Controller />
在这里使用 RHF 的组件。查看文档中的此部分以获取更多信息。
<Controller
control={control}
name="phone"
rules={{ required: true }}
render={({ field: { ref, ...field } }) => (
<ReactPhoneInput
{...field}
inputExtraProps={{
ref,
required: true,
autoFocus: true
}}
country={"in"}
onlyCountries={["in"]}
countryCodeEditable={false}
specialLabel={"Player Mobile Number"}
/>
)}
/>
推荐阅读
- javascript - 在登录页面和仪表板之间拆分视图的最佳方式 Routing Vue js for SPA
- c# - SignalR 在 2020 年是否相关?
- python - “KMeans”对象没有属性“_n_threads”
- aspen - 将数据发布到 Aspen IP21 Historian
- json - Hive/Athena:创建表时忽略字段
- java - 从 JavaFx 中的 DatePicker 中删除边框
- reactjs - 图像导入在反应 js app.js 文件中不起作用?
- django - 如何在elasticsearch文档django中添加搜索索引?
- python - 为什么我无法使用 load_data() 方法加载 mnist 数据集?
- python-3.x - 通过 smtplib 和 python 发送链接