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){
res
.result
.map((item
, index
) => {
item
.key
= index
;
})
this.setState({
dataSource
:res
.result
})
}
})
}
固定表头
官方文档:需要指定 column 的 width 属性,否则列头和内容可能不对齐。如果指定 width 不生效或出现白色垂直空隙,请尝试建议留一列不设宽度以适应弹性布局,或者检查是否有超长连续字段破坏布局
需要指定 column 的 width 属性添加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分页
自定义分页组件
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{
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 width
= item
.width
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)
}
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)
}
else if(item
.type
=== "CHECKBOX"){
const CHECKBOX = <FormItem label
={label
} key
={field
}>
{
getFieldDecorator([field
], {
valuePropName
: 'checked',
initialValue
: item
.initialValue
|| true
})(
<Checkbox
>
{label
}
</Checkbox
>
)
}
</FormItem
>
formItemList
.push(CHECKBOX)
}
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
>