问题
My goal is to use a custom component based on Switch (from React Native) in a Formik form. Here is the code of the form component:
class NewPreferences extends React.Component {
render() {
return(
<View style={styles.mainContainer}>
<View style={styles.newPreferencesContainer}>
<Formik
initialValues={{
food: true
}}
onSubmit={async (values, action) => {
await this.props.onSubmitPress(values)
action.setSubmitting(false)
}}
render={({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
isSubmitting,
}) => (
<View style={styles.formikNewPreferences}>
<View style={styles.itemRow}>
<Field
source={images.food.uri}
onChange={handleChange('food')}
value={values.food}
name="food"
component={ToggleButton}
/>
</View>
<TouchableOpacity
style={styles.button}
onPress={handleSubmit}
disabled={isSubmitting}
>
<Text>Login</Text>
</TouchableOpacity>
</View>
)}
/>
</View>
</View>
);
}
The component ToggleButton is the following one:
class ToggleButton extends React.Component<ToggleButtonInterface> {
render() {
return(
<View>
<Image
source={this.props.source}
/>
<Switch
onValueChange={this.props.onChange}
value={this.props.value}
/>
</View>
);
}
}
It appears that toggling the Switch element raises an error: undefined is not an object (evaluating '_a.type'), in the method _handleChange of Switch. Following the documentation of Formik, I thought I simply needed to pass Formik's handleChange in the props of my custom component, so that when Switch is toggled, Formik changes its state, which will then change the props value of Switch.
Could anyone help me on this issue?
回答1:
Formik's handleChange expects to be called with a React.ChangeEvent.
Since the onValueChange of the Switch component will just be invoked with a boolean you need to use Formik's setFieldValue to handle the change.
<Formik
initialValues={{ switch: false }}
onSubmit={ values => console.log(values) }
>
{props => (
<Switch
value={props.values.switch}
onValueChange={value =>
props.setFieldValue('switch', value)
}
/>
)}
</Formik>
来源:https://stackoverflow.com/questions/54422594/formik-using-react-native-switch