简体   繁体   中英

React Native form with Formik not firing handleSubmit

I am building a form in a React Native app using Formik.

The form doesn't fire the handleSubmit when I click on the button:

<ButtonLoading
    loading={isLoading || isSubmitting}
    label="Salvar"
    style={styles.button}
    onPress={handleSubmit}
/>

Here is my full code for this form:

 import React, { Component, Fragment } from 'react'; import { View, ScrollView } from 'react-native'; import { withFormik } from 'formik'; class Form extends Component { state = { isCepChecked: false, isLoading: false, isNewAddress: true, }; onChangeCep = () => { // Not related to the problem }; render() { const { isCepChecked, isLoading } = this.state, { values, errors, touched, setFieldValue, setFieldTouched, handleSubmit, isSubmitting, } = this.props; return ( <View style={styles.container}> <ScrollView style={styles.formContainer}> {!isCepChecked ? ( <Fragment> <View style={styles.lineContent}> <InputComponent label="Digite o CEP" name="nrCepPre" value={values.nrCepPre} error={errors.nrCepPre} touched={touched.nrCepPre} onTouch={setFieldTouched} onChange={setFieldValue} keyboardType="phone-pad" mask={'[00000]-[000]'} /> </View> <View style={styles.lineContent}> <ButtonLoading isLoading={isLoading || isSubmitting} label="Avançar" style={styles.button} onPress={() => this.onChangeCep()} /> </View> </Fragment> ) : ( <Fragment> <View style={styles.lineContent}> <InputComponent label="CEP" value={values.nrCep} mask={'[00000]-[000]'} editable={false} /> </View> <View style={styles.lineContent}> <InputComponent label="Identificação" name="dsEndereco" value={values.dsEndereco} error={errors.dsEndereco} touched={touched.dsEndereco} onTouch={setFieldTouched} onChange={setFieldValue} /> </View> <View style={styles.lineContent}> <ButtonLoading loading={isLoading || isSubmitting} label="Salvar" style={styles.button} onPress={handleSubmit} /> </View> </Fragment> )} </ScrollView> </View> ); } } export default withFormik({ mapPropsToValues: (props) => ({ nrCepPre: '', dsEndereco: '', nrCep: '', }), validationSchema: enderecoSchema, handleSubmit(values, customObject, bag) { console.warn('handle'); }, })(Form); 

Why not include your handleSubmit() func in your Form class instead by defining it as _hanlderSubmit = (e) = {...} so that there isn't a need for binding it. Then just call it as this._handleSubmit .

You can find more on arrow notation here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM