Redux表单 - 如何将字段设置为触摸

时间:2016-09-01 13:23:21

标签: redux react-redux redux-form

我正在处理由多个页面组成的表单,我想解决验证问题。

当我点击“提交”按钮时,当前页面上的所有字段都显示错误消息,但是如果我更改页面,则需要再次点击提交,因为这些字段未设置为已触摸。

如果我可以将页面上的所有字段设置为触摸,一旦表单具有标记<?php $data = get_file_contents("htmlFile.html"); echo $data; >? ,我的问题就会得到解决。

我使用anyTouched: true并且我有一个容器,其中包含redux-form和包含字段的多个组件。

3 个答案:

答案 0 :(得分:9)

我认为你的问题恰恰相反,但是如果有人在这里登陆,我会在触摸表格中的任何字段后设置anyTouched的方法......

redux-form 6及以上中,您必须使用表单级配置touchOnChangetouchOnBlur - see the docs here明确选择所需的行为 - 默认情况下没有配置任何内容,因此没有任何反应。

const Form = reduxForm({
  form: 'my-form',
  touchOnChange: true,
  touchOnBlur: true
})(...)

这些标记使得任何给定字段都被标记为已触摸(因此anyTouched在表单上标记为true)当该字段的onChangeonBlur处理程序时被称为。

答案 1 :(得分:4)

我应该看起来更好:

Redux表单返回touch作为组件的prop。该函数将字段名称作为参数,因此当componentWillUpdate发生变化时,我会在submitFailed中进行检查,然后我会触及所有无效的字段。

componentWillUpdate(nextProps) {
    const {
      formName: { syncErrors },
      submitFailed,
      touch
    } = this.props

    if (submitFailed !== nextProps.submitFailed) {
      const toTouch = []

      for (const key in syncErrors) {
        syncErrors.hasOwnProperty(key) && toTouch.push(key)
      }
      touch(...toTouch)
    }
  }

答案 2 :(得分:0)

以Redux格式7.4.2。这可以通过检查表单是否有效来实现。

如果有效,则可以加载其他页面之一。 如果表单无效,请使用reduxForms getFormSyncErrors 选择器,并将此对象返回的键传递给reduxForm touch 属性。

import React, { Component } from 'react'
import { compose } from 'redux';
import { connect } from 'react-redux';
import { reduxForm, getFormSyncErrors } from 'redux-form';

class MyComponent extends Component {

  ...

  this.props.valid ? 
    // navigate away 
    : this.props.touch(...Object.keys(this.props.formErrors))

  ...

}

function mapStateToProps(state) {
  return {
    formErrors: getFormSyncErrors('myForm')(state)
  }
}

export default compose(
  connect(mapStateToProps, null),
  reduxForm({form: 'myForm'})
)(MyComponent)
相关问题