【共享单车】—— React后台管理系统开发手记:AntD Form基础组件

前言:以下内容基于React全家桶+AntD实战课程的学习实践过程记录。最终成果github地址:https://github.com/66Web/react-antd-manager,欢迎star。


 一、使用Form组件开发登录页面

 

  • pages->form->login.js:对应路由/admin/form/login
import React from 'react'
import {Card, Form, Input, Button, message, Icon, Checkbox} from 'antd'

const FormItem = Form.Item

class FormLogin extends React.Component{
    handleSubmit = () => {
        let userInfo = this.props.form.getFieldsValue();
        this.props.form.validateFields((err, values) => {
            if(!err){
                message.success(`${userInfo.userName} 恭喜你,您通过本次表单组件学习,当前密码为:${userInfo.userPwd}`)
            }
        })
    }

    render(){
        const { getFieldDecorator } = this.props.form;
        return (
            <div>
                <Card title="登录行内表单">
                    <Form layout="inline">
                        <FormItem>
                            <Input placeholder="请输入用户名"/>
                        </FormItem>
                        <FormItem>
                            <Input placeholder="请输入密码"/>
                        </FormItem>
                        <FormItem>
                            <Button type="primary">登录</Button>
                        </FormItem>
                    </Form>
                </Card>
                <Card title="登录水平表单" style={{marginTop:10}}>
                    <Form layout="horizontal" style={{width:300}}>
                        <FormItem> 
                            {
                                getFieldDecorator('userName', {
                                    initialValue:'Elena',
                                    rules:[
                                        {
                                            required: true,
                                            message:'用户名不能为空'
                                        },
                                        {
                                            min:5, max:10,
                                            message: '长度不在范围内'
                                        },
                                        {
                                            pattern: new RegExp('^\\w+$','g'),
                                            message: '用户名必须为字母或数字'
                                        }
                                    ]
                                })(
                                <Input prefix={<Icon type="user"/>} placeholder="请输入用户名"/>
                                )
                            }  
                        </FormItem>
                        <FormItem>
                            {
                                getFieldDecorator('userPwd', {
                                    initialValue:'123456',
                                    rules:[
                                        {
                                            required: true,
                                            message:'密码不能为空'
                                        },
                                        {
                                            min:6, max:8,
                                            message: '长度不在范围内'
                                        }
                                    ]
                                })(
                                <Input prefix={<Icon type="lock"/>} type="password" placeholder="请输入密码"/>
                                )
                            }
                        </FormItem>
                        <FormItem>
                            {
                                getFieldDecorator('remember', {
                                    valuePropName: 'checked',
                                    initialValue: true,
                                })(
                                   <Checkbox>记住密码</Checkbox>
                                )
                            }
                            <a href="#" style={{float:'right'}}>忘记密码</a>
                        </FormItem>
                        <FormItem>
                            <Button type="primary" onClick={this.handleSubmit}>登录</Button>
                        </FormItem>
                    </Form>
                </Card>
            </div>
        )
    }
}

export default Form.create()(FormLogin);
  • Form组件
  1. layout属性:表示表单布局 -- inline行内表单/horizontal水平表单
  2. getFieldDecorator属性:帮助进行初始化值,获取数据
  3. getFieldDecorator(‘表单里的一些对象’,定义的规则和值)(组件)
    {
          getFieldDecorator('userName', {
                 initialValue:'Elena',
                 rules:[
                      {
                            required: true,
                            message:'用户名不能为空'
                      },
                      {
                            min:5, max:10,
                            message: '长度不在范围内'
                      },
                      {
                            pattern: new RegExp('^\\w+$','g'),
                            message: '用户名必须为字母或数字'
                      }
                  ]
          })(
                  <Input prefix={<Icon type="user"/>} placeholder="请输入用户名"/>
          )
    }  
    

    需要在组件最下方添加 ↓:(经过 Form.create 包装的组件将会自带 this.props.form 属性

    export default Form.create()(FormLogin);
  4. prefix属性:加前缀,使用Icon组件添加小图标

     <Input prefix={<Icon type="user"/>} placeholder="请输入用户名"/>
  5. 指定表单的宽度

    style={{width:300}}
    
  6. 设置记住密码框默认选中
     {
           getFieldDecorator('remember', {
                  valuePropName: 'checked',
                  initialValue: true,
           })(
                  <Checkbox>记住密码</Checkbox>
           )
    }
  • options.rules校验规则
  1. required:是否必选
  2. min : 最小长度
  3. max : 最大长度
  4. len : 字段长度
  5. partten : 正则表达式
  6. type: 内建校验类型  类型选项 

二、使用Form组件开发注册页面

 

  • pages->form->register.js:对应路由/admin/form/reg
import React from 'react'
import moment from 'moment'
import {Card,Form,Input,Button,Checkbox,Radio,InputNumber,Select,Switch,DatePicker,TimePicker,Upload,Icon,message} from 'antd'

const FormItem = Form.Item
const RadioGroup = Radio.Group
const Option = Select.Option;
const TextArea = Input.TextArea

class FormRegister extends React.Component {
    state = {
        loading: false,
    };
    handleSubmit = () => {
        let userInfo = this.props.form.getFieldsValue();
        console.log(JSON.stringify(userInfo))
        message.success(`${userInfo.userName} 恭喜你,您通过本次表单组件学习,当前密码为:${userInfo.userPwd}`)
    }
    handleResetInfo = () => {
        this.props.form.resetFields();
    }
    //模拟上传jpg -- 直接从官网复制过来即可 
    getBase64 = (img, callback) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    }
    handleChange = (info) => {
        if (info.file.status === 'uploading') {
          this.setState({ loading: true });
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          this.getBase64(info.file.originFileObj, imageUrl => this.setState({
            userImg: imageUrl,
            loading: false,
          }));
        }
    }
    render(){
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: 24,
                sm: 4
            },
            wrapperCol: {
                xs: 24,
                sm: 12
            }
        }
        const offsetLayout = {
            wrapperCol: {
                xs: 24,
                sm: {
                    span:12, 
                    offset:4
                }
            }
        }
        const rowObject = {
            minRows: 4, 
            maxRows: 6   
        }
        return (
            <div>
                <Card title="注册表单">
                    <Form layout="horizontal">
                        <FormItem label="用户名" {...formItemLayout}>
                           {
                                getFieldDecorator('userName', {
                                    initialValue:'Elena',
                                    rules:[
                                        {
                                            required: true,
                                            message:'用户名不能为空'
                                        }
                                    ]
                                })(
                                <Input placeholder="请输入用户名"/>
                                )
                            }  
                        </FormItem>
                        <FormItem label="密码" {...formItemLayout}>
                            {
                                getFieldDecorator('userPwd', {
                                    initialValue:'123456',
                                    rules:[
                                        {
                                            required: true,
                                            message:'密码不能为空'
                                        }
                                    ]
                                })(
                                <Input type="password" placeholder="请输入密码"/>
                                )
                            }
                        </FormItem>
                        <FormItem label="性别" {...formItemLayout}>
                            {
                                getFieldDecorator('sex', {
                                    initialValue:'1'
                                })(
                                   <RadioGroup>
                                       <Radio value="1">女</Radio>
                                       <Radio value="2">男</Radio>
                                   </RadioGroup>
                                )
                            }
                        </FormItem>
                        <FormItem label="年龄" {...formItemLayout}>
                            {
                                getFieldDecorator('age', {
                                    initialValue:'18'
                                })(
                                   <InputNumber /> 
                                )
                            }
                        </FormItem>
                        <FormItem label="当前状态" {...formItemLayout}>
                            {
                                getFieldDecorator('state', {
                                    initialValue:'1'
                                })(
                                   <Select>
                                       <Option value="1">咸鱼一条</Option>
                                       <Option value="2">人民公仆</Option>
                                       <Option value="3">浙传才女一枚</Option>
                                       <Option value="4">科技公司FE</Option>
                                       <Option value="5">创业者</Option>
                                   </Select>
                                )
                            }
                        </FormItem>
                        <FormItem label="爱好" {...formItemLayout}>
                            {
                                getFieldDecorator('state', {
                                    initialValue:['1','3','5']
                                })(
                                   <Select mode="multiple">
                                       <Option value="1">旅行</Option>
                                       <Option value="2">读书</Option>
                                       <Option value="3">剪辑</Option>
                                       <Option value="4">拍照</Option>
                                       <Option value="5">看电影</Option>
                                   </Select>
                                )
                            }
                        </FormItem>
                        <FormItem label="是否已婚" {...formItemLayout}>
                            {
                                getFieldDecorator('isMarried', {
                                    valuePropName: 'checked',
                                    initialValue: true
                                })(
                                  <Switch />
                                )
                            }
                        </FormItem>
                        <FormItem label="生日" {...formItemLayout}>
                            {
                                getFieldDecorator('birthday', {
                                    initialValue: moment('2019-1-1 11:14:59')
                                })(
                                  <DatePicker 
                                       showTime
                                       format="YYYY-MM-DD HH:mm:ss"
                                  />
                                )
                            }
                        </FormItem>
                        <FormItem label="联系地址" {...formItemLayout}>
                            {
                                getFieldDecorator('address',{
                                    initialValue: '西虹市海淀区桃花公园'
                                })(
                                  <TextArea 
                                      autosize={rowObject}
                                  />
                                )
                            }
                        </FormItem>
                        <FormItem label="早起时间" {...formItemLayout}>
                            {
                                getFieldDecorator('time')(
                                  <TimePicker />
                                )
                            }
                        </FormItem>
                        <FormItem label="头像" {...formItemLayout}>
                            {
                                getFieldDecorator('userImg')(
                                  <Upload
                                      listType="picture-card"
                                      showUploadList={false}
                                      action="//jsonplaceholder.typicode.com/posts/"
                                      onChange={this.handleChange}
                                  >
                                  {this.state.userImg?<img src={this.state.userImg}/>:<Icon type="plus"/>}
                                  </Upload>
                                )
                            }
                        </FormItem>
                        <FormItem {...offsetLayout}>
                            {
                                getFieldDecorator('imooc')(
                                   <Checkbox>我已阅读过<a href="#">慕课协议</a></Checkbox>
                                )
                            }
                        </FormItem>
                        <FormItem {...offsetLayout}>
                             <Button type="primary" onClick={this.handleSubmit}>提交</Button>
                             <Button style={{marginLeft:10}} onClick={this.handleResetInfo}>重置</Button>
                        </FormItem>
                    </Form>
                </Card>
            </div>
        )
    }
}

export default Form.create()(FormRegister);
  • Form支持响应式尺寸
    //Form组件内嵌的栅格布局
    const formItemLayout = {
                labelCol: {
                    xs: 24,
                    sm: 4
                },
                wrapperCol: {
                    xs: 24,
                    sm: 12
                }
    }
    //偏移布局
    const offsetLayout = {
                wrapperCol: {
                    xs: 24,
                    sm: {
                        span:12, 
                        offset:4  //向右偏移4列
                    }
                }
     }
    
  • 数字框:<InputNumber/>

  • 时间类组件: DatePicker

  1. value 类型为 moment 对象,所以在提交服务器前需要预处理
  2. 安装moment

    yarn add moment --save
  3. 引用moment

    import moment from "moment";
    ……
    <FormItem label="生日" {...formItemLayout}>
           {
                 getFieldDecorator('birthday', {
                         initialValue: moment('2019-1-1 11:14:59')
                 })(
                         <DatePicker 
                                  showTime
                                  format="YYYY-MM-DD HH:mm:ss"
                          />
                  )
            }
    </FormItem>
    
  • 获取表单中Object对象

  1. 调用getFieldsValue方法:获取一组输入控件的值,如不传入参数,则获取全部组件的值

    let userInfo = this.props.form.getFieldsValue();
  2. 重置表单内容:调用resetFields方法 

    this.props.form.resetFields()
    
  3. 注意:使用 getFieldsValue、getFieldValue、setFieldsValue 等时,需要确保对应的 field 已经用 getFieldDecorator 注册过了

  4. 其它Api:官网文档 

  • 上传文件类组件:Upload
  1. action属性:上传的服务器地址
  2. listType属性:上传列表的内建样式  text/picture/picture-card
  3. showUploadList属性:是否展示上传列表内容 {false}↑ 或{true}↓
  4. onChange属性:上传文件状态改变的回调,详见 onChange
  5. 使用Upload组件必需的几个方法:
     //模拟上传jpg -- 直接从官网复制过来即可 
    getBase64 = (img, callback) => {
            const reader = new FileReader();
            reader.addEventListener('load', () => callback(reader.result));
            reader.readAsDataURL(img);
    }
    handleChange = (info) => {
            if (info.file.status === 'uploading') {
              this.setState({ loading: true });
              return;
            }
            if (info.file.status === 'done') {
              // Get this url from response in real world.
              this.getBase64(info.file.originFileObj, imageUrl => this.setState({
                userImg: imageUrl,
                loading: false,
              }));
            }
    }

注:项目来自慕课网

猜你喜欢

转载自www.cnblogs.com/ljq66/p/10204437.html