近期项目中对于展示数据的table有一个特殊需求:
1.数据不够时,要求table的高度撑满页面空白区域
2.没有数据时展示暂无数据的logo
第一个思路肯定是写一个自定义公共组件,包裹一个table,在组件内部设置table的特殊样式,和自定义方法。
高阶组件为可以说是操作props的最优方案。关于原理和使用方法,官网文档介绍非常翔实,https://react.docschina.org/docs/higher-order-components.html。本文介绍一下实际运用。
我定义一个高级组件,命名为EmptyTableHOC,代码如下
import React, {Component} from 'react';
import {Table, Button} from 'antd';
import PropTypes from 'prop-types';
const EmptyTableHOC = (WrappedComponent) =>
class Wrapper extends Component {
emptyText = (height) => {
if (this.props.emptyBtnText) {
let loading = this.props.emptyBtnLoading
return (
<div style={{height: (height - 32) + 'px'}}>
<i className='icon font_family icon-pic-empty empty-icon-style'></i>
<div>暂无数据</div>
<div style={{marginTop: '20px'}}>
<Button loading={loading} type="primary"
onClick={() => this.props.emptyBtnAction()}>{this.props.emptyBtnText}</Button>
</div>
</div>
)
} else {
return (
<div style={{height: (height - 32) + 'px'}}>
<i className='icon font_family icon-pic-empty empty-icon-style'></i>
<div>暂无数据</div>
</div>
)
}
}
componentDidMount() {
}
componentWillReceiveProps = (nextProps) => {
if (document.getElementsByClassName('ant-table-body') && nextProps.dataSource && nextProps.dataSource.length > 0) {
let height = this.props.tableBodyHeight + 'px';
document.getElementsByClassName('ant-table-body')[0].style.height = height;
document.getElementsByClassName('ant-table-body')[0].style.maxHeight = height;
} else {
if (document.getElementsByClassName('ant-table-body') && this.props.dataSource.length != 0) {
document.getElementsByClassName('ant-table-body')[0].style.height = 0;
}
}
}
render() {
const {components, tableBodyHeight} = this.props;
return <WrappedComponent
{...this.props}
components={components ? components : {body: {}}}
locale={{emptyText: () => this.emptyText(tableBodyHeight)}}
/>;
}
};
export default EmptyTableHOC;
使用方式如下:
import React, {Component} from 'react';
import {Modal, Table} from 'antd';
import EmptyTableHOC from "./emptyTableLynn";
const MytableC = EmptyTableHOC(Table);
export default class CopyMetaDataModal extends Component {
constructor(props) {
super(props);
this.state = {
selectedIds: [],
dataSource: []
}
}
render() {
const rowSelection = {
onChange: this.onChange,
selectedRowKeys: this.state.selectedIds
};
return (
<div>
<Modal
title="主数据模型"
visible={this.props.visible}
onOk={this.handleSubmit}
onCancel={this.props.handleCancel}
okText="确认"
cancelText="取消"
>
<MytableC
columns={columns}
rowSelection={rowSelection}
dataSource={this.state.dataSource}
className="mapping-table-scroll"
indentSize={20}
pagination={false}
tableBodyHeight={330}
scroll={{ y: 330 }}
/>
</Modal>
</div>
)
}
}