首页 > 解决方案 > Formik 按钮最初未禁用

问题描述

我正在使用 Formik 验证,如果未满足验证模式,我将尝试禁用该按钮。它应该是一个电话号码,所以如果我输入字母,该按钮将被禁用。有用。

但是,最初当我打开屏幕并且文本字段为空时,该按钮仍应被禁用。但事实并非如此。即使验证模式说“必需”。我怎样才能解决这个问题?

<Formik
              initialValues={initialValues}
              onSubmit={handleSubmitForm}
              validationSchema={validationSchema}>
              {({ handleChange, handleBlur, handleSubmit, values, isValid }) => (
                <View style={styles.searchFieldContainer}>
                  <View style={styles.form}>
                    <FieldInput style={styles.fieldInput}
                      handleChange={handleChange}
                      handleBlur={handleBlur}
                      value={values.phoneNumber}
                      fieldType="phoneNumber"
                      icon="phone"
                      placeholderText="49152901820"
                    />
                    <ErrorMessage
                      name="phoneNumber"
                      render={(msg) => (
                        <Text style={styles.errorText}>{msg}</Text>
                      )}
                    />
                  </View>
                  <View style={styles.buttonContainer}>
                <Button
                  block
                  success
                  disabled={!isValid}
                  onPress={handleSubmit}
                  style={styles.button}>
                  <Text>Speichern</Text>
                </Button>
                  </View>
                </View>
              )}
            </Formik>
const phoneNumberValidationSchema = yup.object().shape({
  phoneNumber: yup
    .string()
    .label('phoneNumber')
    .required('Bitte gebe deine Handynummer ein.')
    .matches(/^[0-9]*$/, 'Bitte nur Ziffern eingeben.'),
});

标签: javascriptreactjstypescriptreact-nativeformik

解决方案


尝试将组件isInitialValid上的 prop设置为.Formikfalse

<Formik
  initialValues={initialValues}
  onSubmit={handleSubmitForm}
  validationSchema={validationSchema}
  isInitialValid={false}
>
  ...
</Formik>

推荐阅读