遇到一个antd中form验证的奇葩问题

Posted by Turingdo Studio on March 22, 2018

antd 组件form验证的奇葩问题

问题?

当把Input组件设置为disabled的时候,验证提醒还会出现,经过查找api都无法完美解决,或者解决后会出现这样或那样的奇葩问题

解决

  1. 伪造一个模样一样的组件,但要将rules属性删掉。
  2. 给伪装组件加一个自定义的key

实例

DEMO

Edit yqlw84n361

关键代码

{this.state.isDisabled ? (
          <FormItem {...formItemLayout} label="E-mail" key="self">
            <Input disabled />
          </FormItem>
        ) : (
          <FormItem {...formItemLayout} label="E-mail">
            {getFieldDecorator("email", {
              disabled: true,
              rules: [
                {
                  type: "email",
                  message: "The input is not valid E-mail!",
                  disabled: true
                },
                {
                  required: true,
                  message: "Please input your E-mail!"
                }
              ]
              })(<Input  />)}
          </FormItem>
        )}

或者可以通过控制input组件的显示隐藏(添加,删除)解决

关键代码

{!this.state.isDisabled ? (
          <FormItem {...formItemLayout} label="E-mail">
            {getFieldDecorator("email", {
              disabled: true,
              rules: [
                {
                  type: "email",
                  message: "The input is not valid E-mail!",
                  disabled: true
                },
                {
                  required: true,
                  message: "Please input your E-mail!"
                }
              ]
              })(<Input  />)}
          </FormItem>
        ) : null}