如何给react-phone-number-input的inputComponent传递Props?
给react-phone-number-input的自定义输入组件传递额外Props
当然可以给TextFieldPhoneInput传递额外Props,最直接的方式是通过包装组件来实现,具体有两种常见写法:
1. 使用匿名组件直接传递
把TextFieldPhoneInput包裹在一个匿名函数组件中,先接收PhoneInput默认传递的所有Props,再展开传递的同时添加你需要的额外属性(比如验证相关的error和helperText):
<PhoneInput international defaultCountry="BD" placeholder="Enter phone number" value={phoneNumber} onChange={handlePhoneNumberOnChange} countryCallingCodeEditable={false} inputComponent={(props) => ( <TextFieldPhoneInput {...props} // 继承PhoneInput提供的默认Props error={!!phoneError} // 自定义错误状态(根据你的验证逻辑赋值) helperText={phoneError} // 自定义错误提示文本 /> )} />
其中phoneError是你根据手机号验证逻辑生成的错误信息(比如为空、格式不正确时的提示文本),当验证不通过时,error设为true,helperText显示对应的错误内容即可。
2. 抽离成可复用的自定义组件
如果需要在多个地方复用这个带验证的输入组件,可以把包装逻辑抽成单独的组件,再通过PhoneInput传递额外Props:
// 定义带额外Props的自定义输入组件 const CustomTextFieldPhoneInput = ({ phoneError, ...restProps }) => { return ( <TextFieldPhoneInput {...restProps} error={!!phoneError} helperText={phoneError} /> ); }; // 在PhoneInput中使用 <PhoneInput international defaultCountry="BD" placeholder="Enter phone number" value={phoneNumber} onChange={handlePhoneNumberOnChange} countryCallingCodeEditable={false} inputComponent={CustomTextFieldPhoneInput} phoneError={phoneError} // 传递额外的验证错误信息 />
这种方式更适合复杂场景,能让代码结构更清晰,也方便后续维护。
内容的提问来源于stack exchange,提问作者Anwar Hossain
相关产品推荐
相关产品推荐

