记录react hooks+Ant Design + react-drag-listview实现Table拖拽变换列位置,方便以后查阅。
首先安装第三方插件库react-drag-listview,命令如下
npm install --save react-drag-listview
一.组件封装
(hooks方法)
import React,{useState} from 'react';
import { Table } from 'antd';
import ReactDragListView from 'react-drag-listview';
const DragTable = (props) => {
const [Columns,setColumns]= useState(props.columns);
const { components, columns, ...others } = props;
const dragProps = {
onDragEnd(fromIndex, toIndex) {
const columns = [...Columns];
const item = columns.splice(fromIndex, 1)[0];
columns.splice(toIndex, 0, item);
setColumns(columns);
},
nodeSelector: 'th',
};
return (
<ReactDragListView.DragColumn {...dragProps}>
<Table columns={Columns} {...others}></Table>
</ReactDragListView.DragColumn>
);
};
export default DragTable;
(class方法)
import React from 'react';
import { Table } from 'antd';
import ReactDragListView from 'react-drag-listview';
class DragTable extends React.Component {
constructor(props) {
super(props);
this.state = {
columns: this.props.columns
}
}
render() {
const { components, columns, ...others } = this.props;
const that = this;
const dragProps = {
onDragEnd(fromIndex, toIndex) {
const columns = [...that.state.columns];
const item = columns.splice(fromIndex, 1)[0];
columns.splice(toIndex, 0, item);
that.setState({
columns
});
},
nodeSelector: "th"
};
return (<ReactDragListView.DragColumn {...dragProps}>
<Table
columns={this.state.columns}
{ ...others }
></Table>
</ReactDragListView.DragColumn>)
}
}
export default DragTable;
二.引用
import React from 'react';
import DragTable from './DragTable';
const StuPub=()=>{
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
render: text => <a>{text}</a>,
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
},
{
title: 'Tags',
key: 'tags',
dataIndex: 'tags',
},
{
title: 'Action',
key: 'action',
dataIndex: 'action',
},
];
const dragTable=[
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
tags: ['nice', 'developer'],
action:'a',
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
tags: ['loser'],
action:'b',
},
{
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sidney No. 1 Lake Park',
tags: ['cool', 'teacher'],
action:'c',
},
]
return <>
<DragTable
columns={columns}
rowKey='id'
dataSource={dragTable}
size='small'
pagination={false}
style={{marginTop: 10}}
rowClassName={(record, index) => {}}
/>
</>
}
export default StuPub;