大家好,欢迎来到IT知识分享网。
具体参数查看官方文档:ProTable – 高级表格 – ProComponents
- 想要实现外部传递进来的参数,每次参数变化,重新请求接口
useEffect(async () => {
if (props?.values?.orgCode) {
if (actionRef.current) {
actionRef.current.reload();
}
}
}, [props?.values?.orgCode, props?.values?.busiPolicyCode]);
<ProTable
actionRef={actionRef}
rowKey={(record) => record.chrecordId}
collapseRender={false}
scroll={
{ x: 1600 }}
//自定义搜索栏按钮
search={
{
labelWidth: 80,
collapsed: false,
collapseRender: () => null,
}}
toolBarRender={null}
options={false}
request={(params) => {
if (props?.values?.orgCode) {
return queryPageOrgPolicyHis({
...params,
currentPage: params.current,
orgCode: props?.values?.orgCode,
busiPolicyCode: props?.values?.busiPolicyCode
}).then((res) => {
if (res.code === '000000') {
const result = {
data: res.data,
total: res.pager.totalSize,
pageSize: res.pager.pageSize,
current: res.pager.currentNum,
};
return result;
} else {
return message.error(res.msg);
}
});
}
}}
columns={columns}
pagination={
{ defaultPageSize: 5, showQuickJumper: true }}
/>
- protable支持的valuetype
通用配置总览 – ProComponents
- 让表格每一列等宽
<ProTable
tableLayout="fixed"
......
/>
- 隐藏选中之后,上面显示的那一列
<ProTable
rowSelection={
{
selectedRowKeys: selectedRowsState?.map(item => item.fieldName),
onChange: (_, selectedRows) => {
setSelectedRows(selectedRows);
},
}}
tableAlertRender={false}
tableAlertOptionRender={false}
......
/>
- hideInSearch: true添加之后,表示在查询中不查询该列
const columns = [
{
title: '规则名称',
dataIndex: 'name',
tip: 'The rule name is the unique key',
hideInSearch: true,
render: (dom, entity) => {
return (
<a
onClick={() => {
setCurrentRow(entity);
setShowDetail(true);
}}
>
{dom}
</a>
);
},
},
...
]
- 隐藏展开、收起,同时增加导出
<ProTable
collapseRender={false}
//自定义搜索栏按钮
search={
{
labelWidth: 120,
//隐藏展开、收起
collapsed: false,
collapseRender:()=>false
//增加导出按钮
optionRender: (searchConfig, formProps, dom) => [<Button key="out">导出</Button>, ...dom],
}}
...
/>
- 隐藏表格内容的右侧按钮:options={false}或者{ fullScreen: false, reload:false , setting: false }关闭单个工具
<ProTable
...
options={false}
/>
- 固定某一列
给需要固定的这一列添加
width: 180,
fixed: 'right',
然后在ProTable标签上面添加scroll={
{ x: 1000 }},不要设置太小,设置值太小不能呈现固定效果
- 不显示总共的数据量
pagination={
{ showTotal: '' }}
- 自定义查询列表样式
const columns = [
{
title: '创建时间',
dataIndex: 'updatedAt',
valueType: 'dateTime',
colSize: 1.5,
renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
const dateFormat = 'YYYY-MM-DD';
return (
<RangePicker
format={dateFormat}
placeholder={['开始时间', '结束时间']}
style={
{ textAlign: 'center' }}
/>
);
},
},
]
- 合并行
const getRowSpans = (arr, key) => {
let sameValueLength = 0;
const rowSpans = [];
for (let i = arr.length - 1; i >= 0; i--) {
if (i === 0) {
rowSpans[i] = sameValueLength + 1;
continue;
}
if (arr[i][key] === arr[i - 1][key]) {
rowSpans[i] = 0;
sameValueLength++;
} else {
console.log(sameValueLength);
rowSpans[i] = sameValueLength + 1;
sameValueLength = 0;
}
}
return rowSpans;
};
const tableData = [...省略]
const rowSpans = getRowSpans(tableData, 'name');
const columns = [
{
title: '配置项',
dataIndex: 'name',
render: (value, _, index) => {
const obj = {
children: value,
props: {},
};
obj.props.rowSpan = rowSpans[index];
return obj;
},
},
]
- 自定义一个展开、收起,收起状态下显示两行
import { UpOutlined, DownOutlined } from '@ant-design/icons';
import {
Col,
Row,
Space,
Button,
Input,
DatePicker,
Select,
} from 'antd';
const { Option } = Select;
const { RangePicker } = DatePicker;
import { useState } from 'react';
import ProTable from '@ant-design/pro-table';
import styles from '../../../common.less';
const dateFormat = 'YYYY-MM-DD';
const TableList = () => {
const [expand, changeExpand] = useState(false);
const [expandText, changeExpandText] = useState('展开');
//判断屏幕分辨率大小,大屏一行4个,小屏一行3个
const updateSize = document.querySelector('body').offsetWidth;
const rowNum = updateSize > 1600 ? 7 : 5;
const getFields = (Query, expand) => {
const count = expand ? Query.length : rowNum;
const children = [];
for (let i = 0; i < count; i++) {
children.push(Query[i]);
}
return children;
};
const getSpanNumber = (number) => {
const count = Query.length % (24 / number);
console.log('===========count', count);
const spanValue = 24 - count * number;
console.log('=========spanValue', spanValue);
return spanValue;
};
const columns = [
{
title: 'CSN号',
dataIndex: 'industryName',
},
];
let Query = [
<Col key="0" lg={12} xl={8} xxl={6}>
<Row>
<Col span={6} className={styles.labelColNew}>
<label>CSN号:</label>
</Col>
<Col span={18}>
<Input allowClear placeholder="请输入" />
</Col>
</Row>
</Col>,
<Col key="1" lg={12} xl={8} xxl={6}>
<Row>
<Col span={6} className={styles.labelColNew}>
<label>机身SN号:</label>
</Col>
<Col span={18}>
<Input allowClear placeholder="请输入" />
</Col>
</Row>
</Col>,
<Col key="2" lg={12} xl={8} xxl={6}>
<Row>
<Col span={6} className={styles.labelColNew}>
<label>绑定商户号:</label>
</Col>
<Col span={18}>
<Input allowClear placeholder="请输入" />
</Col>
</Row>
</Col>,
<Col key="3" lg={12} xl={8} xxl={6}>
<Row>
<Col span={6} className={styles.labelColNew}>
<label>绑定门店号:</label>
</Col>
<Col span={18}>
<Input allowClear placeholder="请输入" />
</Col>
</Row>
</Col>,
<Col key="4" lg={12} xl={8} xxl={6}>
<Row>
<Col span={6} className={styles.labelColNew}>
<label>内部终端号:</label>
</Col>
<Col span={18}>
<Input allowClear placeholder="请输入" />
</Col>
</Row>
</Col>,
<Col key="5" lg={12} xl={8} xxl={6}>
<Row>
<Col span={6} className={styles.labelColNew}>
<label>绑定状态:</label>
</Col>
<Col span={18}>
<Select
style={
{ width: '100%' }}
placeholder="请选择"
onChange={() => {
// setValue(value);
}}
>
<Option value="all">所有</Option>
<Option value="no">未绑定</Option>
<Option value="yes">已绑定</Option>
</Select>
</Col>
</Row>
</Col>,
<Col key="6" lg={12} xl={8} xxl={6}>
<Row>
<Col span={6} className={styles.labelColNew}>
<label>所属机构:</label>
</Col>
<Col span={18}>
<Input allowClear placeholder="请输入" />
</Col>
</Row>
</Col>,
<Col key="7" lg={12} xl={8} xxl={6}>
<Row>
<Col span={6} className={styles.labelColNew}>
<label>所属代理商:</label>
</Col>
<Col span={18}>
<Input allowClear placeholder="请输入" />
</Col>
</Row>
</Col>,
<Col key="8" lg={12} xl={8} xxl={6}>
<Row>
<Col span={6} className={styles.labelColNew}>
<label>设备类别:</label>
</Col>
<Col span={18}>
<Select
style={
{ width: '100%' }}
placeholder="请选择"
onChange={() => {
// setValue(value);
}}
>
<Option value="all">所有</Option>
<Option value="no">未绑定</Option>
<Option value="yes">已绑定</Option>
</Select>
</Col>
</Row>
</Col>,
<Col key="9" lg={12} xl={8} xxl={6}>
<Row>
<Col span={6} className={styles.labelColNew}>
<label>设备厂商:</label>
</Col>
<Col span={18}>
<Select
style={
{ width: '100%' }}
placeholder="请选择"
onChange={() => {
// setValue(value);
}}
>
<Option value="all">所有</Option>
<Option value="no">未绑定</Option>
<Option value="yes">已绑定</Option>
</Select>
</Col>
</Row>
</Col>,
<Col key="10" lg={12} xl={8} xxl={6}>
<Row>
<Col span={6} className={styles.labelColNew}>
<label>设备型号:</label>
</Col>
<Col span={18}>
<Select
style={
{ width: '100%' }}
placeholder="请选择"
onChange={() => {
// setValue(value);
}}
>
<Option value="all">所有</Option>
<Option value="no">未绑定</Option>
<Option value="yes">已绑定</Option>
</Select>
</Col>
</Row>
</Col>,
<Col key="11" lg={12} xl={8} xxl={6}>
<Row>
<Col span={6} className={styles.labelColNew}>
<label>政策编号:</label>
</Col>
<Col span={18}>
<Input allowClear placeholder="请输入" />
</Col>
</Row>
</Col>,
<Col key="12" lg={12} xl={8} xxl={6}>
<Row>
<Col span={6} className={styles.labelColNew}>
<label>入库时间:</label>
</Col>
<Col span={18}>
<RangePicker format={dateFormat} />
</Col>
</Row>
</Col>,
<Col key="13" lg={12} xl={8} xxl={6}>
<Row>
<Col span={6} className={styles.labelColNew}>
<label>出库时间:</label>
</Col>
<Col span={18}>
<RangePicker format={dateFormat} />
</Col>
</Row>
</Col>,
<Col key="14" lg={12} xl={8} xxl={6}>
<Row>
<Col span={6} className={styles.labelColNew}>
<label>绑定时间:</label>
</Col>
<Col span={18}>
<RangePicker format={dateFormat} />
</Col>
</Row>
</Col>,
];
return (
<div className={styles.tableHasQuery}>
{Query.length ? (
<div className={styles.searchFormBox}>
<Row>
<Col span={24}>
<Row>
{getFields(Query, expand)}
<Col
xl={getSpanNumber(8)}
xxl={getSpanNumber(6)}
flex={1}
className={styles.labelColNew}
>
<Space>
<Button type="primary">查询</Button>
<Button>重置</Button>
{Query.length > rowNum ? (
<a
style={
{ marginLeft: 10 }}
onClick={() => {
if (expand) {
changeExpand(false);
changeExpandText('展开');
} else {
changeExpand(true);
changeExpandText('收起');
}
}}
>
{expandText}
{expand ? <UpOutlined /> : <DownOutlined />}
</a>
) : null}
</Space>
</Col>
</Row>
</Col>
</Row>
</div>
) : null}
<ProTable
rowKey="key"
collapseRender={false}
scroll={
{ x: 2200 }}
//自定义搜索栏按钮
search={false}
options={false}
columns={columns}
/>
</div>
);
};
export default TableList;
less文件
.labelColNew{
text-align:right;
height: 28px;
line-height: 28px;
margin-bottom: 20px;
}
.tableHasQuery {
display: flex;
flex-direction: column;
max-height: calc(100vh - 128px);
overflow-y:scroll;
-ms-overflow-style: none;
overflow: -moz-scrollbars-none;
:global {
.ant-pro-table {
flex: 1;
overflow:visible;
}
}
}
.tableHasQuery::-webkit-scrollbar { width: 0 !important }
.searchFormBox {
padding: 20px 20px 0;
background-color: white;
margin-bottom: 20px;
}
- 自定义刷新表格
//首先声明
const selectRef = useRef();
//在Protable中绑定属性
actionRef={actionRef}
//在需要刷新处调用
if (actionRef.current) {
actionRef.current.reload();
}
- 重置所有搜索条件
ref.current.reset();
其实也是用的上面的那个actionRef
// 刷新
ref.current.reload();
// 刷新并清空,页码也会重置,不包括表单
ref.current.reloadAndRest();
// 重置到默认值,包括表单
ref.current.reset();
// 清空选中项
ref.current.clearSelected();
// 开始编辑
ref.current.startEditable(rowKey);
// 结束编辑
ref.current.cancelEditable(rowKey);
- 目前点击表格重置按钮,会重新请求表格。想要点击重置,只是条件置空,但是不重新请求
<ProTable
actionRef={actionRef}
rowKey={(record) => record.categroyCode}
collapseRender={false}
scroll={
{ x: 2000 }}
//自定义搜索栏按钮
search={
{
labelWidth: 120,
collapsed: false,
collapseRender: () => null,
optionRender: ({ searchText, resetText }, { form }) => [
<Button key="out" onClick={() => {}}>
导出
</Button>,
<Button
key="reset"
onClick={() => {
form?.resetFields();
// form?.submit();//刷新表格
}}
>
{resetText}
</Button>,
<Button
type="primary"
key="search"
onClick={() => {
form?.submit();
}}
>
{searchText}
</Button>,
],
}}
toolBarRender={() => [
<Button
type="primary"
onClick={() => {
changeCreateModalVisible(true);
setCurrentRow(undefined);
}}
>
<PlusOutlined /> 添加
</Button>,
]}
options={false}
request={(params) => {
return getEquipCategroyPage({
...params,
currentPage: params.current,
}).then((res) => {
const result = {
data: res.data,
total: res.pager.totalSize,
pageSize: res.pager.pageSize,
current: res.pager.currentNum,
};
return result;
});
}}
columns={columns}
pagination={
{ defaultPageSize: 10, showQuickJumper: true }}
/>
- 在最后一栏操作中,正常render函数返回一个数组,就会有间距,但是容易犯一些小错误,比如render写成renderText函数,没有写valueType:option都会导致没有间距
{
title: '操作',
valueType: 'option',
width: 100,
fixed: 'right',
align: 'center',
render: (_, record) => [
<a onClick={() => {}}>
查看
</a>,
<a onClick={() => {}}>
修改
</a>,
],
},
- 给搜索框手动赋值
const columns = [
...,
{
title: '编号',
dataIndex: 'classesId',
initialValue: '测试数据',
...
},
...
]
- 超长连续字段(长数字和长单词) 破坏表格布局的问题(即使你指定了列的宽度也会被挤开)
解决办法--给ProTable组件设置tableLayout="fixed"
<ProTable
tableLayout="fixed"
......
/>
- Warning: Each child in a list should have a unique “key” prop.
1、如果proTable中遇到,设置rowKey为我们请求出来的数据里面的唯一标识
- 自定义proTable的request
request={(params) =>
getIndustry({ ...params, currentPage: params.current, pageSize: 10 }).then((res) => {
const result = {
data: res.data,
total: res.pager.totalSize,
pageSize: res.pager.pageSize,
current: res.pager.currentNum,
};
return result;
})
}
- 搜索栏的按钮获取搜索框输入的查询条件
// 赋值
form.setFieldsValue({
"date": moment("自定义默认日期", 'YYYY-MM-DD')
})
// 获取对应字段名的值
form.getFieldValue('name')
// 获取Form全部字段名对应的值,会按照对应结构返回。用法
form.getFieldsValue()
<ProTable
actionRef={actionRef}
rowKey={(record) => record.id}
collapseRender={false}
scroll={
{ x: 1800 }}
//自定义搜索栏按钮
search={
{
span: 6,
labelWidth: 100,
collapsed: false,
collapseRender: () => null,
optionRender: ({ searchText, resetText }, { form }) => [
<Button onClick={() => {
let data = form.getFieldsValue()
console.log(data)
}}>
导出
</Button>,
],
}}
toolBarRender={null}
options={false}
request={fetchData}
columns={columns}
pagination={
{ defaultPageSize: 10, showQuickJumper: true }}
/>
- 通过form给表格设置默认值,并且修改某个值
具体用法和form内一样,只不过得定义一个formRef
import { message, DatePicker } from 'antd';
import ProTable from '@ant-design/pro-table';
import { useRef, useEffect } from 'react';
import moment from 'moment';
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
const historyModal = (props) => {
const actionRef = useRef();
const formRef = useRef();
useEffect(() => {
if (props?.values?.userNo) {
if (actionRef.current) {
formRef.current.setFieldsValue({ accChangeDate: [moment(new Date(), dateFormat), moment(new Date(), dateFormat)] })
actionRef.current.reload();
}
}
}, [props?.values?.userNo])
const columns = [
{
title: '收支时间',
dataIndex: 'accChangeDate',
valueType: 'date',
width: 180,
initialValue: [moment(new Date(), dateFormat), moment(new Date(), dateFormat)],
renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
return (
<RangePicker
format={dateFormat}
placeholder={['开始时间', '结束时间']}
style={
{ textAlign: 'center', width: '100%' }}
onChange={(dates, dateStrings) => {
console.log('========dateStrings', dateStrings)
if (formRef.current) {
formRef.current.setFieldsValue({ accChangeDate: [dateStrings[0] ? moment(dateStrings[0]) : '', dateStrings[1] ? moment(dateStrings[1]) : ''] })
}
}}
/>
);
},
},
];
return (
<ProTable
size="small"
actionRef={actionRef}
...
request={(params) => {
let accChangeDate = formRef.current.getFieldValue('accChangeDate') || params?.accChangeDate
...
} else {
console.log('========请选择收支时间')
message.error('请选择收支时间');
}
}}
columns={columns}
pagination={
{ defaultPageSize: 5, showQuickJumper: true }}
formRef={formRef}
/>
);
};
export default historyModal;
- 表格内超出内容区域,字段隐藏
添加 ellipsis: true
const columns = [
{
title: '用户姓名',
dataIndex: 'userName',
width: 160,
ellipsis: true,
},
]
- 表格没有上面的操作按钮时,设置toolBarRender={null}
如果设置为toolBarRender={false},表格会失去padding
- 隐藏表格表头title
Table标记加属性 showHeader={false}
<ProTable
...
showHeader={false} //隐藏表格title
/>
- 搜索栏:自定义一个可全选的下拉查询
transform自定义表格查询搜索列表的查询字段
https://blog.csdn.net/qq_37815596/article/details/125184438?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22125184438%22%2C%22source%22%3A%22qq_37815596%22%7D&ctrtid=ZagTX
const [selectState, setCheckStatus] = useState(true)
const [selectList, setSelectList] = useState(['1', '2', '3', '4', '5'])
const columns = [
{
title: '统计日期',
dataIndex: 'reportTime',
hideInTable: true,
valueType: 'dateRange',
initialValue: [
moment().subtract(1, 'days').format('YYYY-MM-DD'),
moment().format('YYYY-MM-DD')
],
//transform自定义表格查询列表的查询字段
transform: v => ({
reportStartTime: moment(v[0]).format('YYYYMMDD'),
reportEndTime: moment(v[1]).format('YYYYMMDD')
}),
fieldProps: {
allowClear: false
}
},
{
title: '交易方式',
dataIndex: 'tradeWay',
width: 180,
initialValue: ['1', '2', '3', '4', '5'],
valueEnum: tradeValue,
renderFormItem: () => (
<Select
mode="multiple"
onChange={value => {
setSelectList(value)
if (formRef.current) {
formRef.current.setFieldsValue({ tradeWay: value })
}
}}
dropdownRender={allSelectValue => (
<div>
<div style={
{ padding: '4px 8px 8px 8px', cursor: 'pointer' }}>
<Checkbox
checked={selectState && selectList?.length === tradeList?.length}
onChange={e => {
if (e.target.checked === true) {
setCheckStatus(true) //选中时 给 checked 改变状态
setSelectList(['1', '2', '3', '4', '5'])
// 当选的时候 把所有列表值赋值给tradeWay
if (formRef.current) {
formRef.current.setFieldsValue({
tradeWay: tradeList?.map(item => item.value)
})
}
} else {
setCheckStatus(false)
setSelectList([])
if (formRef.current) {
formRef.current.setFieldsValue({ tradeWay: [] })
}
}
}}
>
全部
</Checkbox>
</div>
{/* Option 标签值 */}
{allSelectValue}
</div>
)}
>
{tradeList?.map(item => (
<Option key={item.value} value={item.value}>
{item.label}
</Option>
))}
</Select>
)
},
{
title: '所属服务商',
dataIndex: 'agentName',
valueType: 'treeSelect',
width: 140,
initialValue: localCache.getItem('agentCode'),
fieldProps: {
placeholder: '请选择',
allowClear: true,
options: agentTree,
fieldNames: {
children: 'children',
label: 'agentName',
value: 'agentCode'
}
},
ellipsis: true
},
]
<ProTable
formRef={formRef}
actionRef={actionRef}
rowKey={(record) => record.id}
collapseRender={false}
scroll={
{ x: 1800 }}
//自定义搜索栏按钮
search={
{
span: 6,
labelWidth: 100,
collapsed: false,
collapseRender: () => null,
optionRender: ({ searchText, resetText }, { form }) => [
<Button onClick={() => {}}>
导出
</Button>,
],
}}
toolBarRender={null}
options={false}
request={...}
columns={columns}
pagination={
{ defaultPageSize: 10, showQuickJumper: true }}
/>
- 设置 column.ellipsis 报错[antd: Typography] `ellipsis` should use string as children only.
原因:ellipsis:true 只能用在返回为字符串的列
- 搜索栏内,设置禁用日期:disabledDate
const columns = [
{
title: '日期',
dataIndex: 'reportTime',
hideInTable: true,
valueType: 'dateRange',
initialValue: [
moment().subtract(1, 'days').format('YYYY-MM-DD'),
moment().format('YYYY-MM-DD')
],
transform: v => ({
reportStartTime: moment(v[0]).format('YYYYMMDD'),
reportEndTime: moment(v[1]).format('YYYYMMDD')
}),
fieldProps: {
allowClear: false,
picker: 'date',
format: 'YYYY-MM-DD',
disabledDate: current => current && current > moment().subtract(1, 'date').endOf('date')
}
},
]
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/10806.html