如何与React-Phone-number输入的LIB成为朋友?
我正在尝试使用Formik,Material UI和React-Phone-number输入LIB(用于电话号码格式)来开发一种表单。我遇到了一个问题。输入电话号码时,已经按预期进行了格式,但是该号码未插入formik state。因此,在formik中看不到电话号码值,因此,当输入某个值时,Formik无法将错误标记“必需”带走。猜测之后,我以不正确的方式使用了反应手机输入的lib和formik。如何正确使用它们?
我有基本文件src/app.js。我使用PhonenumberInput组件的位置。这实际上是我的电话号码输入。
export const App = () => {
return (
<>
<Formik
initialValues={{
firstName: '',
lastName: '',
email: '',
phoneNumber: '',
}}
validationSchema={Yup.object({
firstName: Yup.string()
.max(15, 'Have to be 15 characters or less')
.required('Required'),
lastName: Yup.string()
.max(20, 'Have to be 20 or less characters')
.required('Required'),
email: Yup.string().required('Required.'),
phoneNumber: Yup.string().required('Required'),
})}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2))
setSubmitting(false)
}, 400)
}}
>
{context => (
<Form>
<MainContainer>
<Title text={'Step 2'} iconRender={<AccountCircleRoundedIcon />} />
<TextInput text={'Email'} name={'email'} />
<PhoneNumberInput
name={'phoneNumber'}
label={'Phone Number'}
context={context}
/>
<MyButton>Next</MyButton>
</MainContainer>
</Form>
)}
</Formik>
</>
)
}
在src/components/phonenumberinput/phonenumberinput.js中,我定义了PhonenumberInput组件。 我使用来自React-Phone-number输入的输入组件,有机会使用自定义输入。
const MyField = React.forwardRef(function custom(props, ref) {
const { name, label } = props
return (
<Field
{...props}
component={TextField}
label={label}
name={name}
variant="outlined"
inputRef={ref}
fullWidth
/>
)
})
export const PhoneNumberInput = ({ text, ...props }) => {
const [value, setValue] = useState()
const [focus, setFocus] = useState(false)
console.log(props.context)
return (
<>
<Input
{...props}
country="UA"
international={focus}
value={value}
withCountryCallingCode
onChange={setValue}
inputComponent={MyField}
onFocus={() => setFocus(true)}
control={props.control}
/>
</>
)
}
怎么了?如何解决这个问题?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,在Formik Hooks的帮助下实现非常容易,
这是我的工作解决方案:
然后在您的Formik表单中使用此组件
Actually it's pretty easy to implement with the help of Formik hooks
This is my working solution:
Then use this component in your Formik Form as so