当不再需要输入字段时,如何自动显示错误消息?

时间:2019-06-26 10:04:47

标签: javascript reactjs antd

我正在使用antd input field并尝试在o/p状态和 class ABCApiService extends ApiService { create() { return this.post("/...") .then(res => res.json()) .catch((error) => { console.log(error); }); } update() { return this.post("/...") .then(res => res.json()) .catch((error) => { console.log(error); }); } delete() { return this.post("/...") .then(res => res.json()) .catch((error) => { console.log(error); }); } } export class ApiService { constructor() { this.apiURL = "http://localhost:3000/data"; this.headerOption = { headers: { "Content-Type": "application/json", "Accept": "application/json" } }; this.abcApi = new ABCApiService(); } post(api, data) { const options = { method: "POST", body: JSON.stringify(data), ...this.headerOption }; return fetch(this.apiURL + api, options); } } 状态之间切换,我注意到一种特殊情况,即当输入字段为时错误消息不会消失。不再需要。我不确定required = true为什么不自行处理这种情况。

这是我的工作:

  • 输入字段初始化为required=false
  • 我写了些东西然后擦除,如图所示,出现消息“请输入您的用户名”
  • 然后单击antd按钮。这样会将输入字段的状态从required更改为Click to toggle input field
  • 但是错误消息仍然存在。当不再需要输入字段时,如何自动显示错误消息?

enter image description here

这是我在codeandbox上创建的上述图像的小演示:

Edit determined-williams-cctpp

这也是代码:

required = true

1 个答案:

答案 0 :(得分:0)

似乎无法实现这种行为,因为Form.Item仅在onInput调用上(当您在Input内部输入内容时)设置新的验证状态,因此它不采用“ required”开关考虑在内。

如果您需要更改验证行为,可以使用以下简单解决方案:

{enable ? 
      (<Form.Item>
      {getFieldDecorator('username', {
        rules: [{ required: this.state.enable, message: 'Please input your username!' }],
      })(
        <Input disabled = {!enable}
        />,
      )}
    </Form.Item>) :
   <Form.Item>
     <Input disabled = {!enable} />
   </Form.Item>`}

此解决方案的唯一警告是,它将在更改“启用”开关时隐藏先前输入的值,但是您可以将其保存在状态中的任何位置,然后将默认输入值分配给此“输入的状态”的值值”