如何与react-phone-number-input lib加好友Formik ?



我正在尝试使用Formik, Material UI和React-phone-number-input lib(用于电话号码格式化)开发表单。我遇到了一个问题。当输入电话号码时,一个号码已经按照预期格式化,但是该号码没有插入到Formik状态。因此,电话号码值对于Formik是不可见的,因此,当输入某些值时,Formik无法删除错误标记"required"。猜到之后,我以不正确的方式同时使用了react-phone-number-input lib和Formik。如何正确使用它们?

github: https://github.com/AlexKor-5/FormChallenge/tree/0d37064ef54c8e87a6effb950575a5a3817d9220

我有基础文件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-input的Input组件,以便有机会使用自定义输入。

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}
/>
</>
)
}

怎么了?如何解决这个问题?

实际上在Formik hooks的帮助下很容易实现

这是我的工作解决方案:

import PhoneInput from "react-phone-number-input";
import { useField } from "formik";
import FieldWrapper from "../FieldWrapper";
const PhoneInputField = ({ label, ...props }) => {
const [field, meta, helpers] = useField(props.name);
return (
<FieldWrapper label={label} meta={meta} {...props}>
<PhoneInput
{...props}
{...field}
value={field.value}
defaultCountry="NO"
onChange={(value) => {
helpers.setValue(value);
}}
/>
</FieldWrapper>
);
};
export default PhoneInputField;

然后在Formik表单中使用这个组件,如下

// your boilerplate code ect...
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={onSubmit}
>
{({ handleSubmit, isSubmitting }) => (    
<FieldPhoneInput
label="Phone Number"
name="phone"
type="tel"
placeholder="Write your phone number here"
/>
)}
</Formik>

最新更新