Redux 表单:输入保持 'touched: false'

Redux Form: Input stays with 'touched: false'

想要验证我的输入并根据用户交互更改 CSS。

从一个必需的验证方法开始,我用一个 <Field> 包装了我所有的输入组件,并传递给 validate 一个函数数组。现在只有 required

但对于我的所有字段,值保持不变 touched: falseerror: "Required"。如果我在输入中触摸或添加内容,这些值将保持不变。

验证

export const required = value => (value ? undefined : 'Required')

NameInput

import React from 'react';
import { Field } from 'redux-form'
import InputItem from 'Components/InputsUtils/InputItem';
import { required } from 'Components/InputsUtils/Validation';

const NameInput = () => (
  <Field
    name={item.spec.inputName}
    type={item.spec.type}
    component={InputItem}
    validate={[required]}
    props={item}
  />
);

export default NameInput;

输入项

import React from 'react';

const InputItem = ({ spec, meta: { touched, error } }) => {        
  const { type, placeholder } = spec;
  return (
    <input
      className="input"
      type={type}
      placeholder={placeholder}
    />
  );
};

export default InputItem;

redux-form 在您的 <input /> 元素中控制它自己的道具,只要您使用传播运算符将这些道具传递到您的输入中。

例如,你在哪里做const InputItem = ({ spec, meta: { touched, error } }) => ...

尝试破坏组件的输入:const InputItem = ({ input, spec, meta: { touched, error } }) => ...

在你有 <input ... /> 的地方,尝试执行以下操作:

<input
  {...input}
  className="input"
  type={type}
  placeholder={placeholder}
/>

redux-form 捕获任何 onBluronChange 事件并使用其自己的方法来更改 touched 状态。你只需要像上面那样传递它们。

这些是您需要的:https://redux-form.com/7.1.2/docs/api/field.md/#input-props

有 2 个解决方案可以解决 "touched is always false" 问题。

1) 确保在您的组件中调用 input.onBlur

对于输入:

const { input } = this.props

<input {...input} />

对于没有原生的自定义表单元素onBlur

const { input: { value, onChange, onBlur } } = this.props

const className = 'checkbox' + (value ? ' checked' : '')

<div
  className={className}
  onClick={() => {
    onChange(!value)
    onBlur()
  }}
/>

2) 使用 touchOnChange

声明您的表单
const ReduxFormContainer = reduxForm({
  form: 'myForm',
  touchOnChange: true,
})(MyForm)

还有一点需要考虑: 我将 {...props} 传递给了我的自定义组件,但是 touched 仍然是 false。 那是因为虽然 props 包含输入对象,但我的组件不能 从中推断出 onBlur 。当明确声明 <CustomComponent {...this.props} onBlur={this.props.input.onBlur} 时,它按预期工作。