安装

开始使用FixedDataTable的最简单方法是通过npm安装它:

npm install react --save
npm install fixed-data-table-2 --save

如果您使用的是标准构建系统(例如browserifywebpack),则可以直接使用require方式引入:

const React = require('react');
const {Table, Column, Cell} = require('fixed-data-table-2');

对于布局和样式,需要添加默认样式表:fixed-data-table-2/dist/fixed-data-table.min.css

构建你的 Table#

可以通过Table组件设置表格。为了能够处理大量的数据,该表只呈现那些对用户可见的部分,为了计算这个,静态的widthheightrowsCountrowHeight是必需的:

const React = require('react');
const {Table} = require('fixed-data-table-2');
class MyTable extends React.Component {
render() {
return (
<Table
rowsCount={100}
rowHeight={50}
width={1000}
height={500}>
// TODO: Add columns
</Table>
);
}
}

自定义数据#

通常,您将希望按行呈现自定义数据,让我们向表中添加一些数据,并为该列添加标题。

const React = require('react');
const {Table, Column, Cell} = require('fixed-data-table-2');
class MyTable extends React.Component {
constructor(props) {
super(props);
this.state = {
myTableData: [
{name: 'Rylan'},
{name: 'Amelia'},
{name: 'Estevan'},
{name: 'Florence'},
{name: 'Tressa'},
],
};
}
render() {
return (
<Table
rowsCount={this.state.myTableData.length}
rowHeight={50}
headerHeight={50}
width={1000}
height={500}>
<Column
header={<Cell>Name</Cell>}
cell={props => (
<Cell {...props}>
{this.state.myTableData[props.rowIndex].name}
</Cell>
)}
width={200}
/>
</Table>
);
}
}

提供了cell属性(当值为函数时返回组件),该函数将传递单元格rowIndexwidthheight。通过使用rowIndex,我们可以从this.state.myTableData[rowIndex]中获取每个单元格的数据。

创建可复用的单元格#

通过自定义组件的方式实现单元格的可复用性,如:以下电子邮箱示例

const React = require('react');
const {Table, Column, Cell} = require('fixed-data-table-2');
class MyTextCell extends React.Component {
render() {
const {rowIndex, field, data, ...props} = this.props;
return (
<Cell {...props}>
{data[rowIndex][field]}
</Cell>
);
}
}
class MyLinkCell extends React.Component {
render() {
const {rowIndex, field, data, ...props} = this.props;
const link = data[rowIndex][field];
return (
<Cell {...props}>
<a href={link}>{link}</a>
</Cell>
);
}
}
class MyTable extends React.Component {
constructor(props) {
super(props);
this.state = {
myTableData: [
{name: 'Rylan', email: 'Angelita_Weimann42@gmail.com'},
{name: 'Amelia', email: 'Dexter.Trantow57@hotmail.com'},
{name: 'Estevan', email: 'Aimee7@hotmail.com'},
{name: 'Florence', email: 'Jarrod.Bernier13@yahoo.com'},
{name: 'Tressa', email: 'Yadira1@hotmail.com'},
],
};
}
render() {
return (
<Table
rowsCount={this.state.myTableData.length}
rowHeight={50}
headerHeight={50}
width={1000}
height={500}>
<Column
header={<Cell>Name</Cell>}
cell={
<MyTextCell
data={this.state.myTableData}
field="name"
/>
}
width={200}
/>
<Column
header={<Cell>Email</Cell>}
cell={
<MyLinkCell
data={this.state.myTableData}
field="email"
/>
}
width={200}
/>
</Table>
);
}
}