我尝试实现mui自定义表,使用可排序和排序解决方案,我是新材料ui并做出反应。如何处理此事件。我创建了这个方法,需要按方向排序:' asc',' desc'。在哪里设置createSortHandler方法。建议最好的解决方案。
const columns = [
{
dataKey: 'deviceType',
label:'Device Type',
}, {
dataKey: 'deviceID',
label:'Device ID',
sortable: true,
// cellRenderer: ({item, dataKey}) =>
// <Button >Default</Button>,
}, {
dataKey: 'name',
label: 'Name',
sortable: true,
},{
dataKey: 'currentVersion',
label: 'Current Version',
sortable: true,
},{
dataKey: 'location',
label: 'Location',
sortable: true,
},{
dataKey: 'status',
label: 'Status',
sortable: true,
},{
dataKey: 'lastAliveMessage',
label: 'Last alive message',
sortable: true,
}, {
dataKey: 'action',
label: 'Actions',
cellRenderer: () => <MoreVertIcon />,
}]
const data = [
{ deviceType: 'Tag', deviceID: 1, name:'Tag For sending an ', location: 'Room_104', status: 'assigned'},
{ deviceType: 'Tag', deviceID: 1, name:'Tag For sending an ', location: 'Room_104', status: 'assigned'},
{ deviceType: 'Tag', deviceID: 1, name:'Tag For sending an ', location: 'Room_104', status: 'assigned'},
{ deviceType: 'Tag', deviceID: 1, name:'Tag For sending an ', location: 'Room_104', status: 'assigned'},
{ deviceType: 'Tag', deviceID: 1, name:'Tag For sending an ', location: 'Room_104', status: 'assigned'},
]
const defaultCellRenderer = ({item, dataKey}) =>
item[dataKey]
const createSortHandler = property => event => {
this.props.onRequestSort(event, property)
};
const Table = ({data, columns, order, orderBy, className,children,...props}) =>
// console.log(columns.map(({dataKey,label}) => dataKey))
// console.log(data.map(item => columns.map(({dataKey, cellRenderer}) => defaultCellRenderer({item,dataKey}))))
<MuiTable >
<TableHead>
<TableRow >
{columns.map(({dataKey, label}) =>
<TableCell compact>
<TableSortLabel active={orderBy = dataKey} direction={order}>
{label}
</TableSortLabel>
</TableCell>)}
</TableRow>
</TableHead>
<TableBody>
{data.map(item =>
<TableRow hover>
{columns.map(({dataKey, cellRenderer}) =>
<TableCell compact>
{(cellRenderer || defaultCellRenderer)({item, dataKey})}
</TableCell>)}
</TableRow>)}
</TableBody>
</MuiTable>
class EnhanceTable extends Component{
state = {
order: 'asc',
orderBy: 'calories',
selected: [],
searchValue: '',
};
handleRequestSort = (event, property) => {
const orderBy = property
let order = 'desc'
if (this.state.orderBy === property && this.state.order === 'desc') {
order = 'asc'
}
const filterData = this.state.filterData.sort(
(a, b) => order === 'desc' ? b[orderBy] > a[orderBy] : a[orderBy] > b[orderBy],
)
this.setState({ filterData, order, orderBy })
};
render() {
const { order, orderBy, selected } = this.state
return(
<Paper style={{width: '100%'}}>
<Table data={data} columns={columns} order={order} orderBy={orderBy} onRequestSort={this.handleRequestSort}/>
</Paper>
)
}
}