React-Antd-表单-基本使用

文档地址: 链接.

import { Form, Input, Button, Checkbox } from "antd";

export default function App() {
  return (
    <Form
      // 设置表单样式
      style={{ width: "800px", border: "1px solid #eee", margin: "20px auto" }}
      // 禁止输入框自动完成
      autoComplete="off"
      // 表单名称,会作为表单字段 id 前缀使用
      // <input type="text" id="basic_username" class="ant-input" value="123">
      name="basic"
      // label 标签布局,同 <Col> 组件,设置 span offset 值,如 {span: 3, offset: 12} 或 sm: {span: 3, offset: 12}
      labelCol={{ span: 8 }}
      // 需要为输入控件设置布局样式时,使用该属性,用法同 labelCol
      wrapperCol={{ span: 16 }}
      // 表单默认值,只有初始化以及重置时生效
      initialValues={{ remember: true }}
      // 提交表单且数据验证成功后回调事件
      onFinish={(values) => {
        console.log("验证成功:", values);
      }}
      // 提交表单且数据验证失败后回调事件
      onFinishFailed={(errorInfo) => {
        console.log("验证失败:", errorInfo);
      }}
    >
      <Form.Item
        // label 标签的文本
        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
        name="remember"
        // 子节点的值的属性,如 Switch 的是 'checked'。该属性为 getValueProps 的封装,自定义 getValueProps 后会失效
        valuePropName="checked"
        wrapperCol={{ offset: 8, span: 8 }}
      >
        <Checkbox>记住我</Checkbox>
      </Form.Item>
      <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
        <Button type="primary" htmlType="submit">
          提交
        </Button>
      </Form.Item>
    </Form>
  );
}

版权声明:本文为big_sun_962464原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。