简体   繁体   English

redux-form v6显示选择字段的验证错误

[英]redux-form v6 show validation error for select field

In v6 of redux-form we can show the errors for normal input fields like following 在redux-form的v6中,我们可以显示正常输入字段的错误,如下所示

We can create custom renderField like this 我们可以像这样创建自定义renderField

const renderField = ({ input, label, type, meta: { touched, error } }) => (
  <div>
    <label>{label}</label>
    <div>
      <input {...input} placeholder={label} type={type}/>
      {touched && error && <span>{error}</span>}
    </div>
  </div>
)

And in the form, just we can use that custom renderField 在表单中,我们可以使用该自定义renderField

 <Field name="username" type="text" component={renderField} label="Username"/>

Now i need to know, How we can do this same for select field, and how should we pass dropdown options to this custom renderFields, Any idea to create custom renderField for select ? 现在我需要知道,我们如何为select字段做同样的事情,以及我们应该如何将dropdown选项传递给这个自定义renderFields,是否有想法为select创建自定义renderField?

If you don't mind some code duplication, you could do it like this: 如果你不介意一些代码重复,你可以这样做:

const renderSelectField = ({ input, label, type, meta: { touched, error }, children }) => (
  <div>
    <label>{label}</label>
    <div>
      <select {...input}>
        {children}
      </select>
      {touched && error && <span>{error}</span>}
    </div>
  </div>
)

Consume it in the form: 以下列形式消费:

<Field name="username" component={renderSelectField} label="Username">
  { mySelectOptions.map(option => <option value={option.value}>{option.text}</option>) }
</Field>

You can see that passing the options to a select is done through props.children , exactly the same as when you would use the Field component with component="select" . 您可以看到将选项传递给select是通过props.children完成的,与使用component component="select"Field组件完全相同。

If you don't want the duplication, you could try to make the original renderField a bit smarter instead. 如果您不想复制,可以尝试使原始的renderField更聪明一些。 For example, you could see if children contains option-tags, and if so, render the <select> instead of the input . 例如,您可以看到children项是否包含选项标记,如果是,则显示<select>而不是input

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM