1. 一定要在Form標籤上添加scrollToFirstError屬性,觸發要使用Button上面的htmlType="submit"方可。注意:Button要在Form標籤內部包裹
<Form
form={form}
scrollToFirstError
onFinish={onSubmit}
>
<Row>
<Col span={8}>
<Item
name="name"
{...layout}
label="承租方名稱(中)"
rules={[{ required: true, message: '請輸入' }]}
>
<Input />
</Item>
</Col>
<Col span={8}>
<Item {...layout} name="english_name" label="承租方名稱(英)">
<Input />
</Item>
</Col>
</Row>
<Button loading={loading} type="primary" htmlType="submit">
</Form>
缺點:不一定能準確的滑動到第一個校驗不通過的Form表單
優點:使用方便,代碼簡潔
2.使用Form提供的校驗不通過的事件來處理
<Form
form={form}
onFinish={onSubmit}
onFinishFailed={() => {
// 核心代碼
const errorList = (document as any).querySelectorAll(".ant-form-item-has-error");
// 由於校驗失敗ant會自動給失敗表單項添加類名,直接獲取即可
errorList[0].scrollIntoView({
block: "center",
behavior: "smooth",
});
}}
>
<Row>
<Col span={8}>
<Item
name="name"
{...layout}
label="承租方名稱(中)"
rules={[{ required: true, message: '請輸入' }]}
>
<Input />
</Item>
</Col>
<Col span={8}>
<Item {...layout} name="english_name" label="承租方名稱(英)">
<Input />
</Item>
</Col>
</Row>
// 這個時候不一定需要把Button放到Form標籤內部也不一定需要使用htmlType屬性
<Button loading={loading} type="primary" htmlType="submit">
</Form>
缺點:需要獲取DOM 代碼量增多
優點:能夠很完美的實現需求同時彌補方案一的短板
總結:如果方案一能滿足您的需求建議使用方案一如果不行再使用方案二,首選方案一