React之Antd组件

React之Antd组件

Modal对话框

Modal.method()动态设置确认框和提示框

    handleConfirm = (type)=>{
        Modal[type]({
            title:'确认?',
            content:'你确定你学会了React了吗?',
            onOk(){
                console.log('Ok')
            },
            onCancel(){
                console.log('Cancel')
            }
        })
    }
    
	render(){
	        return (
	            <div>
	                <Card title="信息确认框" className="card-wrap">
	                    <Button type="primary" onClick={() => this.handleConfirm('confirm')}>Confirm</Button>
	                    <Button type="primary" onClick={() => this.handleConfirm('info')}>Info</Button>
	                    <Button type="primary" onClick={() => this.handleConfirm('success')}>Success</Button>
	                    <Button type="primary" onClick={() => this.handleConfirm('warning')}>Warning</Button>
	                </Card>
	               
	            </div>
	        );
	    }

Spin加载Loading

自定义指示符

 render(){
        const icon = <Icon  type="loading" style={{fontSize:24}}/>
        return (
            <div>
                <Card title="Spin用法" className="card-wrap">
                    <Spin indicator={icon} style={{ marginLeft: 10 }} spinning={true}/>
                </Card>
             </div>
             )
          }

自定义全局默认 Spin 的元素

静态方法

Spin.setDefaultIndicator(indicator: ReactNode)

Notification通知提醒框

    openNotification = (type,direction)=>{
   		//一个全局配置方法,在调用前提前配置,全局一次生效。
        if (direction){
            notification.config({
                placement: direction
            })
        }
        notification[type]({
            message:'发工资了',
            description:'上个月考勤22天,迟到12天,实发工资250,请笑纳'
        });
    }

    render(){
        return (
            <div>
                <Card title="通知提醒框" className="card-wrap">
                    <Button type="primary" onClick={()=>this.openNotification('success')}>Success</Button>
                    <Button type="primary" onClick={()=>this.openNotification('info')}>Info</Button>
                    <Button type="primary" onClick={()=>this.openNotification('warning')}>Warning</Button>
                    <Button type="primary" onClick={()=>this.openNotification('error')}>Error</Button>
                </Card>
                <Card title="通知提醒框" className="card-wrap">
                    <Button type="primary" onClick={() => this.openNotification('success','topLeft')}>Success</Button>
                    <Button type="primary" onClick={() => this.openNotification('info','topRight')}>Info</Button>
                    <Button type="primary" onClick={() => this.openNotification('warning','bottomLeft')}>Warning</Button>
                    <Button type="primary" onClick={() => this.openNotification('error','bottomRight')}>Error</Button>
                </Card>
            </div>
        );

Message全局提示

    showMessage = (type)=>{
        message[type]("恭喜你,操作成功");
    }

    render(){
        return (
            <div>
                <Card title="全局提示框" className="card-wrap">
                    <Button type="primary" onClick={()=>this.showMessage('success')}>Success</Button>
                    <Button type="primary" onClick={()=>this.showMessage('info')}>Info</Button>
                    <Button type="primary" onClick={()=>this.showMessage('warning')}>Warning</Button>
                    <Button type="primary" onClick={()=>this.showMessage('error')}>Error</Button>
                    <Button type="primary" onClick={()=>this.showMessage('loading')}>Loading</Button>
                </Card>
            </div>
        );
    }

Tabs标签页

Tab带图的页签

			    handleCallback = (key)=>{
			        message.info("Hi,您选择了页签:"+key)
			    }
			    
                <Card title="Tab带图的页签" className="card-wrap">
                    <Tabs defaultActiveKey="1" onChange={this.handleCallback}>
                        <TabPane tab={<span><Icon type="plus" />Tab 1</span>} key="1">欢迎学习React课程</TabPane>
                        <TabPane tab={<span><Icon type="edit" />Tab 2</span>} key="2">欢迎学习React课程</TabPane>
                        <TabPane tab={<span><Icon type="delete" />Tab 3</span>} key="3">React是一个非常受欢迎的MV*框架</TabPane>
                    </Tabs>
                </Card>

Switch开关

使用Switch组件无法显示为true状态,需要一个设置额外的属性valuePropName,同样也适用于Checkbox组件

                        <FormItem label="是否已婚" {...formItemLayout}>
                            {
                                getFieldDecorator('isMarried', {
                                    valuePropName:'checked',
                                    initialValue: true
                                })(
                                    <Switch/>
                                )
                            }
                        </FormItem>
  • 效果

Form表单

实现一个简单的登录表单

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="登录水平表单" style={{marginTop:10}}>
                    <Form style={{width:300}}>
                        <FormItem>
                            {
                                getFieldDecorator('userName',{
                                    initialValue:'',
                                    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: '',
                                    rules: []
                                })(
                                    <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);
  • 效果

在这里插入图片描述

Table

简单表格

import React from "react";
import {Card,Table} from "antd";
export default class SimpleTable extends React.Component{
    componentWillMount() {
        const columns = [
            {
                title: '姓名',
                dataIndex: 'name',
                key: 'name',
            },
            {
                title: '年龄',
                dataIndex: 'age',
                key: 'age',
            },
            {
                title: '住址',
                dataIndex: 'address',
                key: 'address',
            },
        ];
        const dataSource = [
            {
                key: '1',
                name: '胡彦斌',
                age: 32,
                address: '西湖区湖底公园1号',
            },
            {
                key: '2',
                name: '胡彦祖',
                age: 42,
                address: '西湖区湖底公园1号',
            },
        ];
        this.setState({
            dataSource,
            columns
        })

    }

    render() {
        return(
            <div>
                <Card title="简单表格">
                    <Table
                        bordered
                        columns={this.state.columns}
                        dataSource={this.state.dataSource}
                    >
                    </Table>
                </Card>
            </div>
        )}
}
  • 效果

动态渲染时数据源key值处理

若后端接口返回的数据没有key字段,可动态添加不影响源数据

	request = ()=>{
        let _this = this;
        axios.ajax({
            url:'/api/v1/getTableData',
            data:{
                params:{
                    page:this.params.page
                }
            }
        }).then((res)=>{
            if(res.code == 0){
                //数据添加key属性,返回新数组,不影响源数据
                res.result.map((item, index) => {
                    item.key = index;
                })
                this.setState({
                    dataSource:res.result
                })
            }
        })
    } 

固定表头

官方文档:需要指定 columnwidth 属性,否则列头和内容可能不对齐。如果指定 width 不生效或出现白色垂直空隙,请尝试建议留一列不设宽度以适应弹性布局,或者检查是否有超长连续字段破坏布局

  1. 需要指定 columnwidth 属性
  2. 添加scroll={{y:240}},数值根据内容调整
				<Table	
                     bordered
                     scroll={{y:240}}
                     columns={this.state.columns}
                     dataSource={this.state.dataSource}
                 />

单选表格行点击单选

通过设置行属性onRow实现单选选中

  onClickRow=(record ,index)=>{
       let selectKeys = [index]
       Modal.info({
           title:'提示',
           content:`用户名:${record.userName},用户爱好:${record.interest}`
       })
        this.setState({
            selectedRowKeys: selectKeys,
            selectedItem:record
        })
   }
   render() {
       const {selectedRowKeys} = this.state
       const rowSelection ={
           type: "radio",
           selectedRowKeys
       }
       return(
         <div>
             <Card title="单选表格">
                 <Table columns={this.state.columns}
                        dataSource={this.state.dataSource}
                        bordered
                        rowSelection={rowSelection}
                        onRow={(record,index) => {
                            return {
                                // 点击行选中
                                onClick: () => {
                                    this.onClickRow(record,index)
                                },
                            };
                        }}
                        pagination={false}>
                 </Table>
             </Card>
         </div>
       );
   }

Pagination分页

自定义分页组件

    /**
     * 基于Antd Pagination分页组件
     * @param data 参数
     * @param callback 回调函数
     * */
    pagination(data,callback){
        return {
            onChange:(current)=>{
                callback(current)
            },
            current:data.result.page,
            pageSize:data.result.page_size,
            total: data.result.total_count,
            showTotal:()=>{
                return `共${data.result.total_count}条`
            },
            showQuickJumper:true
        }
    },
  • 效果

ConfigProvider全局化配置

antd 目前的默认文案是英文,如果需要使用其他语言,可以参考下面的方案

import { ConfigProvider } from 'antd';
import zhCN from 'antd/es/locale/zh_CN';

ReactDOM.render(
    <ConfigProvider locale={zhCN}>
        <Router />
    </ConfigProvider>
    ,
  document.getElementById('root')
);

封装查询组件

  • 效果

定义查询组件

import React from "react";
import {Input, Select, Button, Form, Checkbox, Radio, DatePicker} from "antd"
import "./index.less"
const FormItem = Form.Item
const Option = Select.Option
class SearchForm extends React.Component{

    /** 获取select option项
     * @param data
     * */
    getOptionList=(data)=>{
        if(!data){
            return []
        }
        const options = []
        data.map((item)=>{
            options.push(<Option label={item.title} key={item.key} className="optionItemCss">{item.title}</Option>)
        })
        return  options
    }
    /**
     * 查询,传递查询参数
     * */
    query=()=>{
        //获取表单数据
        const fieldsValue = this.props.form.getFieldsValue();
        this.props.searchFormParam(fieldsValue)
    }
    /**
     * 重置表单数据
     * */
    reset=()=>{
        this.props.form.resetFields();
    }
    //初始化表单数据
    initFormList=()=> {
        const { getFieldDecorator} = this.props.form;
        //获取表单配置参数
        const formList = this.props.formList;
        const formItemList = [];
        if(formList && formList.length > 0){
            formList.forEach((item)=>{
                let label = item.label
                let field = item.field
                let placeholder = item.placeholder
                // let initialValue = item.initialValue
                let width = item.width
                //let list = item.list
                //输入文本框
                if(item.type === "INPUT"){
                    const INPUT = <FormItem label={label} key={field}>
                        {
                            getFieldDecorator([field], {
                                initialValue: item.initialValue
                            })(
                                <Input type="text" placeholder={placeholder} />
                            )
                        }

                    </FormItem>
                    formItemList.push(INPUT)
                }
                //select选择器
                else if(item.type === "SELECT"){
                    const SELECT = <FormItem label={label} key={field}>
                        {
                            getFieldDecorator([field], {
                                initialValue: item.initialValue || []
                            })(
                                <Select
                                    style={{ width: width }}
                                    placeholder={placeholder}
                                >
                                    {this.getOptionList(item.optionList)}

                                </Select>
                            )
                        }

                    </FormItem>
                    formItemList.push(SELECT)
                }
                //checkbox选择器
                else if(item.type === "CHECKBOX"){
                    const CHECKBOX = <FormItem label={label} key={field}>
                        {
                            getFieldDecorator([field], {
                                valuePropName: 'checked',
                                initialValue: item.initialValue || true //true | false
                            })(
                                <Checkbox>
                                    {label}
                                </Checkbox>
                            )
                        }

                    </FormItem>
                    formItemList.push(CHECKBOX)
                }
                //DatePicker(开始 --> 结束)时间段选择器
                else if (item.type == "DATEPICKER"){
                    //开始时间
                    const begin_time = <FormItem label="订单时间" key={field}>
                        {
                            getFieldDecorator('begin_time')(
                                <DatePicker showTime={true} placeholder={placeholder} format="YYYY-MM-DD HH:mm:ss"/>
                            )
                        }
                    </FormItem>;
                    formItemList.push(begin_time)
                    //结束时间
                    const end_time = <FormItem label="~" colon={false} key={field}>
                        {
                            getFieldDecorator('end_time')(
                                <DatePicker showTime={true} placeholder={placeholder} format="YYYY-MM-DD HH:mm:ss" />
                            )
                        }
                    </FormItem>;
                    formItemList.push(end_time)
                }
            })
        }
        return formItemList
    }

    render() {
        return(
            <div>
                <Form layout="inline">
                    { this.initFormList() }
                </Form>
                <FormItem>
                    <Button type="primary" style={{ margin: '0 20px' }} onClick={this.query}>查询</Button>
                    <Button onClick={this.reset}>重置</Button>
                </FormItem>

            </div>
        );
    }
}
export default Form.create({})(SearchForm)

定义查询参数formList

    formList = [
        {
            type:'SELECT',
            label:'城市',
            field:'city',
            placeholder:'全部',
            initialValue:'aa',
            width:80,
            optionList: [{ key: 'aa', title: '全部' }, { key: 'bb', title: '北京' }, { key: 'cc', title: '天津' }, { key: 'dd', title: '上海' }]
        },
        {
            type: 'DATEPICKER'
        },
        {
            type: 'SELECT',
            label: '订单状态',
            field:'order_status',
            placeholder: '全部',
            initialValue: 'sq',
            width: 80,
            optionList: [{ key: 'sq', title: '全部' }, { key: 'se', title: '进行中' }, { key: 'rs', title: '结束行程' }]
        }
    ]

使用组件

             <Card title="搜索组件">
                 <SearchForm formList={this.formList} searchFormParam={this.queryTable}></SearchForm>
             </Card>
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DuebassLei

请我吃颗棒棒糖吧~~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值