问题描述
我的目标是以Formik形式使用基于Switch
的自定义组件(来自React Native).这是表单组件的代码:
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>
);
}
组件ToggleButton
是以下组件:
class ToggleButton extends React.Component<ToggleButtonInterface> {
render() {
return(
<View>
<Image
source={this.props.source}
/>
<Switch
onValueChange={this.props.onChange}
value={this.props.value}
/>
</View>
);
}
}
在Switch
的_handleChange
方法中,似乎切换Switch元素会引发错误:undefined is not an object (evaluating '_a.type')
.遵循Formik的文档,我认为我只需要在自定义组件的props中传递Formik的handleChange
,以便在切换Switch
时,Formik更改其状态,然后将更改value. c0>.有人可以帮我解决这个问题吗?
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?
推荐答案
Formik的handleChange
期望用React.ChangeEvent
调用.由于Switch
组件的onValueChange
只会被布尔值调用,因此您需要使用Formik的setFieldValue
来处理更改.
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>
这篇关于使用React Native Switch的Formik的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!