【问题标题】:Formik + yup not displaying errorsFormik + yup 不显示错误
【发布时间】:2018-09-06 12:58:30
【问题描述】:

我有以下表格:

import React from 'react'
import PanelInputField from './form_components/panel_input_field'
import * as yup from 'yup'
import { withFormik, FormikErrors, FormikProps } from "formik";

const validationSchema = yup.object().shape({
  length: yup
    .number()
    .min(200, 'NOT BIG ENOUGH')
    .required()
})

class SpecificationsForm extends React.PureComponent {
  render() {
    const {
      values,
      handleInputChange,
      handleSelectChange,
      touched,
      errors
    } = this.props;

    console.log(errors)
    return (
      <div className="panel panel-default specifications-panel" id="js-turbosquid-product-specifications-panel">
        <div className="panel-heading">
          <a href="#" className="js-more-info" data-toggle="collapse" data-target="#specifications-panel-instructions" tabIndex="-1">
            Specifications
            <i className="fa fa-question-circle" />
          </a>
        </div>

        <div className="panel-body panel-collapse collapse in" id="specification-panel-body">
          <div className="panel-body-container">
            <div id="specifications-panel-instructions" className="panel-instructions collapse" />

            <div className="row">
              <div className="col-xs-6">

                <PanelInputField 
                  label='Length'
                  value={ values.length }
                  onChange={ handleInputChange } 
                  formName='turbosquid_product_form_length'
                  fieldName='length'
                />
                <div className="form-field-error">{errors.length ? errors.length : "No Error"}</div>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

const ProductSpecificationsMotionCapturePanel = withFormik({
  validationSchema,
  enableReinitialize: true,
  mapPropsToValues: (props) => (props),
  handleInputChange: (props) => (props.handleInputChange),
  handleSelectChange: (props) => (props.handleSelectChange),
})(SpecificationsForm)

export default ProductSpecificationsMotionCapturePanel

表单工作正常,显示和一切,但我似乎无法让 formik 看到错误。在这个例子中,我有整数值的长度字段。每当我输入内容时,验证工作(console.log 打印)但对象完全为空。

即使我在输入中输入非数字,也不会显示任何错误。

有没有人建议我可以做些什么来使它工作?

【问题讨论】:

标签: reactjs formik yup


【解决方案1】:

您是否设置了初始值?看起来你没有在这个文件中。如果没有,请尝试设置它,看看它是否有效。

【讨论】:

  • 此外,您不能将initialValues 设置为空对象(例如const initialValues = {};)。您必须包含要显示错误的字段名称的初始值。例如,const initialValues = { name: '' }; 表示 name 没有初始值。
猜你喜欢
  • 1970-01-01
  • 2022-07-28
  • 1970-01-01
  • 2020-10-14
  • 2020-08-06
  • 1970-01-01
  • 2019-12-10
  • 2020-06-06
  • 2022-01-17
相关资源
最近更新 更多