问题
I have a custom input field for the phone number made from the library 'react-phone-input-2',
I will show the code for the custom input field made by a colleague
<PhoneInput
inputProps={{
name: inputName,
}}
country="lb"
value={phoneNumber}
placeholder="1234456"
onChange={phone => handleInputChange(inputName, phone)}
buttonClass="buttonarrow"
containerStyle={mainContainer}
inputStyle={phoneInput(countryCodeBtnWidth, isMobileScreen, hasError)}
buttonStyle={countryCodeBtn(countryCodeBtnWidth, isMobileScreen)}
dropdownStyle={dropDownList}
/>
When I import this and try to send formik to handle the handleInputOnChange I am not able to extract the values even though all other fields are being extracted in the same way.
I will post code for the extraction
<PhoneInputValidation
name="phoneNumber"
value={formik.phoneNumber}
handleInputChange={formik.handleChange}
hasError={
formik.errors.phoneNumber && formik.touched.phoneNumber
}
validationMessage={ERROR_REQUIRED}
onBlur={formik.handleBlur}
/>
phoneInputValidation is another component made from importing phoneInput the code is below
<ValidationModule hasError={hasError} validationMessage={validationMessage}>
<PhoneInputCustom
handleInputChange={handleInputChange}
hasError={hasError}
inputName={name}
phoneNumber={value}
/>
</ValidationModule>
ps: using formik.handleChange
on other fields in the same form is working fine
回答1:
Formik's handleChange
accepts 2 types of arguments:
- Field name [string]: in this case it returns a functions to which you can pass the change event or value directly
- Change event: in this case it will get the name of the field to update from the change event itself
https://github.com/jaredpalmer/formik/blob/d4049f2da7e2e8811b498ea8013b77af063c6c8a/packages/formik/src/Formik.tsx#L657-L667
Your code only uses the first form:
<PhoneInput
...
onChange={phone => handleInputChange(inputName, phone)}
...
/>
Formik will ignore the phone value in this case. Following samples should work.
<PhoneInput
...
onChange={phone => handleInputChange(inputName)(phone)}
...
/>
OR
<PhoneInput
...
onChange={phone => handleInputChange({
target: {
name: inputName
value: phone
}
})}
...
/>
Also have a look at the documentation of the phone input as it gives more data with the change event than only the phone number:
https://github.com/bl00mber/react-phone-input-2#events
来源:https://stackoverflow.com/questions/61222416/cannot-extract-phone-number-input-from-custom-made-field-using-formik