简体   繁体   English

Form.Item 在 antd 中经过验证后,如何提供回调?

[英]How do I provide a callback when Form.Item has been validated in antd?

My Input currently sits within a <Form> and Form.Item .我的 Input 当前位于<Form>Form.Item中。
I want to trigger a callback only when the validation has been successful, so the callback would not run validation fails.我只想在验证成功时触发回调,所以回调不会运行验证失败。
Is there a way to do that?有没有办法做到这一点?

<Form.Item
  hasFeedback
  name="url"
  rules={[
    {
      required: true,
      min: 5,
      type: "url",
      whitespace: true,
    },
  ]}
  onChange={console.log}
>
  <Input
    name="url"
    onChange={(event) => {
      props.onChange(event);
      setValue(event.target.value);
    }}
  />
</Form.Item>

Reference:参考:

You can achieve this behavior by using Form component's onValuesChange event handler in combination with a useRef and the form.validateFields instance method.您可以通过将Form组件的onValuesChange事件处理程序与useRefform.validateFields实例方法结合使用来实现此行为。 The useRef is used to track the previous validation status of the url field. useRef用于跟踪url字段之前的验证状态。

The callback, as currently setup in the example below, will only launch when the field transitions from an error validation state to a successful validation state (which I assume is the behavior you want).回调,如以下示例中当前设置的那样,仅当字段从错误验证 state 转换为成功验证 state 时才会启动(我假设这是您想要的行为)。

https://codesandbox.io/s/antd-launchcallbackonvalidatesuccess-pehue https://codesandbox.io/s/antd-launchcallbackonvalidatesuccess-pehue

Happy coding!快乐编码!

PS If the url Form.Item component also has access to the form instance, then you should also be able to initiate the same logic using the Input component's onChange handler. PS 如果url Form.Item组件也可以访问form实例,那么您也应该能够使用Input组件的onChange处理程序启动相同的逻辑。

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

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