MuiTelInput与react-hook-form集成异常及默认国旗设置问题
解决MuiTelInput结合react-hook-form的输入异常与默认国家配置问题
一、输入字符被删除+onChange报错的解决方案
问题原因
直接将react-hook-form的register结果展开传递给MuiTelInput会触发参数不匹配:MuiTelInput的onChange回调返回(格式化号码: string, 国家信息: Country),而register生成的onChange期望接收标准React ChangeEvent对象,这种不匹配会抛出Cannot read properties of undefined (reading 'name')错误,进而导致输入字符被立即删除。
修复方案
使用react-hook-form的Controller组件适配非标准表单控件,它能自动处理值同步与验证逻辑的衔接:
import { useForm, Controller } from "react-hook-form"; import MuiTelInput from "mui-tel-input"; export default function RegisterForm() { const { control, formState: { errors } } = useForm({ defaultValues: { phone: "" } }); return ( <form> <Controller name="phone" control={control} rules={{ required: "Please enter your phone number!", minLength: { value: 10, message: "Phone must be made out of at least 10 characters", }, maxLength: { value: 20, message: "Phone can not be longer than 20 characters", }, }} render={({ field }) => ( <MuiTelInput className="w-full" label="Phone number" value={field.value} onChange={(value) => field.onChange(value)} defaultCountry="CN" /> )} /> {/* 显示错误提示 */} {errors.phone && <span style={{ color: "red" }}>{errors.phone.message}</span>} </form> ); }
二、默认国家国旗显示与切换配置
给MuiTelInput添加defaultCountry属性,传入对应国家的两位ISO代码(如中国CN、美国US),组件会默认显示该国家国旗,且自带国家切换下拉菜单,用户点击国旗即可切换其他国家。
如果需要动态修改默认国家,可绑定状态变量实现:
import { useState } from "react"; // ... const [activeCountry, setActiveCountry] = useState("CN"); // 在组件中使用 <MuiTelInput // ...其他属性 defaultCountry={activeCountry} onCountryChange={(country) => setActiveCountry(country.iso2)} />
内容的提问来源于stack exchange,提问作者justelio19
相关产品推荐
相关产品推荐

