在 redux-form 中使用 onBlur

Nar*_*kur 5 javascript reactjs redux redux-form react-redux

我正在使用 redux-form 7.0.4,除了以下问题之外,它工作正常。

新用户可以输入详细信息,现有用户可以在同一表单上编辑详细信息。当现有用户编辑详细信息并从表单字段中删除数据时,我遇到了问题。我想添加检查 onBlur。如果用户为空表单字段并且有模糊事件,我需要在字段内填充初始数据。

如果字段为空,则在模糊时恢复初始/服务器值。

表单字段:

<Field
  component={InputField}
  type='text'
  name='registeredName'
  className='form-control'
  required
  placeholder='Registered Business Name*'
/>
Run Code Online (Sandbox Code Playgroud)

输入字段组件:

const InputField = ({
  input,
  type,
  placeholder,
  meta: { touched, error, initial }
}) => {
  const onChange = (e) => {
    const val = e.target.value;

    if (type === 'phoneNumber') {
      if (!/^\d+$/.test(val) || String(val).length > 10) {
        return;
      }
    }

    input.onChange(e);
  };


  return (
    <div className='form-group'>
      <input
        {...input}
        onChange={onChange}
        type={type}
        className='form-control'
        placeholder={placeholder}
        value={input.value }
        onBlur={e => {input.value = (!e.target.value) ? initial : e.target.value;}}
      />
      {touched &&
       ((error &&
         <div className='error text-danger'>
           {error}
         </div>
       ))}
    </div>
  );
};
/* eslint-enable */

export default InputField;
Run Code Online (Sandbox Code Playgroud)

Dan*_*ion 0

您需要在 Field 组件中设置onChange和 ,如下所示:onBlur

<Field
  component={InputField}
  type='text'
  name='registeredName'
  className='form-control'
  required
  placeholder='Registered Business Name*'
  onChange={(event) => {
      ...your onChange function here...
  }}
  onBlur={(event) => {
      ...Your onBlur function here...
  }}
/>
Run Code Online (Sandbox Code Playgroud)

我建议仔细阅读该组件的文档<Field />

希望这有帮助