【问题标题】:How to show an alert with errors found after submitting Formik form in react nativereact native提交Formik表单后如何显示错误提示
【发布时间】:2019-06-06 06:04:53
【问题描述】:

我在 react 本地和 Yup 验证架构中有一个 Formik 表单。当用户提交表单时,如果存在无效字段,我想创建一个带有错误字段的警报。

Dependencies:
"formik": "^1.4.1",
"react": "16.5.0",
"react-native": "0.57.1",

我尝试在Formik 渲染中使用isValid 并创建一个带有错误的警报,但我得到一个空的错误对象。但是,如果我再次提交/或单击两次提交,则错误对象包含预期的无效字段。

如何在首次提交时获取错误对象?

【问题讨论】:

  • 你有什么解决办法吗?我会很高兴听到。

标签: reactjs react-native formik yup


【解决方案1】:

你应该做的是有一个模态或类似的东西来显示错误。

当使用Formik 时,您渲染的组件(您可以使用componentrenderchildren)将收到带有错误的道具,如您在docs 的示例中所见。

<Formik>                              {// getting the errors here }
  {({ handleSubmit, handleChange, handleBlur, values, errors }) => (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        onChange={handleChange}
        onBlur={handleBlur}
        value={values.name}
        name="name"
      />
      {errors.name &&
        <div>
          {errors.name}
        </div>}
      <button type="submit">Submit</button>
    </form>
  )}
</Formik>

errors 将是一个对象,因此您检查errorskeys(或者您也可以使用values)并决定您是否会呈现错误模式。

<Formik
    validationSchema={yourValidationSchema}
    onSubmit={whatYouWantTodoWhenEverythingIsGood}
    initialValues={{ email: '' }}
>                                 
    {({ errors, values, handleChange, handleBlur}) => (
        <View>
            <TextInput
                onChangeText={handleChange('email')}
                onBlur={handleBlur('email')}
                value={values.email}
            />
            <Button onPress={props.handleSubmit} title="Submit" />
            {// checking if you have errors}
            {
                Object.keys(errors).length > 0 && 
                    <Modal errors={errors}/>
            }
        </View>
  )}
</Formik>

根据您的模态来自哪里,您可以使用&lt;Modal isActive={Object.keys(errors).length &gt; 0} errors={errors}/&gt; 或其他类似的东西。

例如使用react-native modal

<Modal
    visible={Object.keys(errors).length > 0}
>
        <View>
            {// show the errors the way you want}
        </View>
</Modal>

您应该使用Object.keys(errors).length &gt; 0 来决定是否应该使用errors 显示模态框。

【讨论】:

    【解决方案2】:

    这是因为当您在 RN 中单击提交按钮时,触摸的对象没有更新。尝试将空白值设置为具有验证架构的字段的初始值。像这样的:

    initialValues={{ input_1: "", input_2: "" }}
    

    来自 formik git repo 的 answer 帮助了我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 2021-04-25
      • 2022-11-18
      • 1970-01-01
      • 2019-07-16
      • 1970-01-01
      • 2018-02-25
      相关资源
      最近更新 更多