赞
踩
目录
主要用到了Form组件的这两个方法
同时表单内的按钮一定要设置成提交类型
下面是代码演示
- import React from 'react'
- import { Button, Form, Input } from 'antd'
-
- export default function Music() {
- const onFinish = (values) => {
- // values就是表单中输入的值
- console.log('Success:', values)
- }
- const onFinishFailed = (errorInfo) => {
- console.log('Failed:', errorInfo)
- }
- return (
- <div style={{ width: 400, margin: '0 auto' }}>
- <Form
- labelCol={{ span: 4 }}
- onFinish={onFinish}
- onFinishFailed={onFinishFailed}
- autoComplete="off"
- >
- <Form.Item
- label="用户名"
- name="username"
- rules={[
- {
- required: true,
- message: '请输入用户名!',
- },
- ]}
- >
- <Input />
- </Form.Item>
-
- <Form.Item
- label="密码"
- name="password"
- rules={[
- {
- required: true,
- message: '请输入密码!',
- },
- ]}
- >
- <Input.Password />
- </Form.Item>
-
- <Form.Item
- wrapperCol={{
- offset: 8,
- span: 16,
- }}
- >
- <Button type="primary" htmlType="submit">
- 登录
- </Button>
- </Form.Item>
- </Form>
- </div>
- )
- }
获取需要校验的表单的实例化
通过实例化的validateFields方法触发表单验证
这是此方法返回实例
代码演示
- import React, { useState } from 'react'
- import { Modal, Form, Input, Button } from 'antd'
-
- export default function Movie() {
- // 表单实例化 会绑定表单的form值为formInstance的内个表单,一一对应
- const [formInstance] = Form.useForm()
- // 控制对话框的显示/隐藏
- const [isModalOpen, setIsModalOpen] = useState(false)
- // 按钮点击事件
- const showModal = () => {
- setIsModalOpen(true)
- }
- // 对话框点击确定
- const handleOk = () => {
- // 通过表单实例化的validateFields()方法进行校验
- formInstance.validateFields().then((values) => {
- // values就是表单中输入的值
- console.log(values)
- setIsModalOpen(false)
- })
- }
- // 对话框点击取消
- const handleCancel = () => {
- setIsModalOpen(false)
- }
- return (
- <div>
- <Button type="primary" onClick={showModal}>
- 显示对话框
- </Button>
- <Modal
- title="Basic Modal"
- open={isModalOpen}
- onOk={handleOk}
- onCancel={handleCancel}
- >
- <Form form={formInstance} labelCol={{ span: 4 }} autoComplete="off">
- <Form.Item
- label="用户名"
- name="username"
- rules={[
- {
- required: true,
- message: '请输入用户名!',
- },
- ]}
- >
- <Input />
- </Form.Item>
-
- <Form.Item
- label="密码"
- name="password"
- rules={[
- {
- required: true,
- message: '请输入密码!',
- },
- ]}
- >
- <Input.Password />
- </Form.Item>
- </Form>
- </Modal>
- </div>
- )
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。