在React中如何使用react-hook-form获取react-phone-input-2的输入值
问题原因
react-phone-input-2 是封装后的自定义受控组件,没有直接暴露原生输入框的ref,react-hook-form 的 register 方法仅适配原生输入控件,因此直接配置name属性无法被react-hook-form识别取值,需要使用官方提供的Controller组件做第三方组件适配。
完整修改代码
依赖引入和逻辑部分
import ReactPhoneInput from "react-phone-input-2" import {TextField,Button}from "@material-ui/core" // 新增引入Controller import { useForm, Controller } from "react-hook-form" // 解构新增control对象 const { register, handleSubmit, control, formState: { errors }} = useForm() const getData= (data) => { console.log(data.username) // 可以正常拿到手机号数值 console.log(data.phone) }
表单部分
<form onSubmit={handleSubmit(getData)} > <TextField {...register("username")} /> {/* 用Controller包裹ReactPhoneInput做绑定 */} <Controller name="phone" control={control} rules={{ required: '请填写手机号' }} render={({ field }) => ( <ReactPhoneInput {...field} inputExtraProps={{ required: true, autoFocus: true }} country={"in"} onlyCountries={["in"]} countryCodeEditable={false} specialLabel={"Player Mobile Number"} /> )} /> {/* 可选:手机号错误提示 */} {errors.phone && <span style={{color: 'red'}}>{errors.phone.message}</span>} <Button type='submit'>Submit</Button> </form>
内容的提问来源于stack exchange,提问作者ASIF KAIF
相关产品推荐
相关产品推荐

