当前位置:   article > 正文

用表头设置控制表格内列的排序和显示隐藏

用表头设置控制表格内列的排序和显示隐藏

项目背景 : react + ant

需求 :  点击表头设置弹窗 , 拖拽可控制外部表格列的排序 , 开关可控制外部表格列的显示和隐藏

实现效果如下 :


注意 :  1. 拖拽效果参考了ant-table中的拖拽效果(这块代码放最后)  
            2. 后台反了json格式(用is_show控制显示和隐藏 , 我给他传递sort值来控制排序 , 后台返回格式如下~)
            3. 将拖拽和显示隐藏后的内容存到了localStorage

实现 : 
 

  1. const [biaotouData, setBiaotouData] = useState([
  2. {
  3. key: 'orderNumber',
  4. orderNumber: '工单编号'
  5. },
  6. {
  7. key: 'placeName',
  8. orderNumber: '地点'
  9. },
  10. .....
  11. ])
  12. const biaotouColumns = [
  13. {
  14. render: () => <DragHandle /> // 让拖拽图标在第一列
  15. },
  16. {
  17. title: (
  18. <span style={{ color: dropdownOpen1 ? ' var(--main-bg)' : '#333' }}>
  19. {t('HeaderColumn')}
  20. </span>
  21. ),
  22. dataIndex: 'orderNumber',
  23. align: 'center',
  24. key: 'orderNumber'
  25. },
  26. {
  27. title: (
  28. <span style={{ color: dropdownOpen2 ? ' var(--main-bg)' : '#333' }}>
  29. {t('WhetherDisplayed')}
  30. </span>
  31. ),
  32. align: 'center',
  33. dataIndex: 'placeName',
  34. key: 'placeName',
  35. render: (data, record) => (
  36. <div>
  37. <Switch
  38. checked={getIsShowForColumn(record.key)} // 使用getIsShowForColumn函数获取当前列的is_show状态
  39. onChange={data => handleSwitchChange(record, data)}
  40. />
  41. </div>
  42. )
  43. }
  44. ]
  45. const sortedColumns = sortColumnsBySort(tableColumns) // 排序后的列,传递给外部的table
  46. const [biaotouModal, setBiaotouModal] = useState(false) // 控制表头设置的显示隐藏
  47. const [sortData, setSortData] = useState() //拿到表头列的显示状态
  48. // 打开表头设置弹窗
  49. const biaotouHandle = async () => {
  50. setBiaotouModal(true)
  51. const res = await getList7({ type: 3 })
  52. console.log('res.titleSetContent', res.titleSetContent)
  53. setSortData(JSON.parse(res.titleSetContent))
  54. }
  55. // 排序
  56. function sortColumnsBySort (columns) {
  57. return columns.sort((a, b) => a.sort - b.sort)
  58. }
  59. // 在渲染Switch的地方,查找当前列对应的is_show值
  60. const getIsShowForColumn = columnName => {
  61. return sortData?.find(item => item.name === columnName)?.is_show ?? true // 如果找不到,默认为true
  62. }
  63. // 当拖拽和显示和隐藏后外部表格更新
  64. useEffect(() => {
  65. if (sortData) {
  66. const updateAndHandleResponse = async () => {
  67. const res = await getEditMethod3({
  68. titleSetContent: JSON.stringify(sortData),
  69. type: 3
  70. })
  71. localStorage.setItem('hiddenColumns1', JSON.stringify(sortData))
  72. const updatedColumns = tableColumns.map(column => {
  73. if (
  74. sortData.find(
  75. item => item.name === column.key && item.is_show === false
  76. )
  77. ) {
  78. return { ...column, hidden: true }
  79. } else if (
  80. sortData.find(
  81. item => item.name === column.key && item.is_show === true
  82. )
  83. ) {
  84. return { ...column, hidden: false }
  85. }
  86. return column
  87. })
  88. setTableColumns(updatedColumns)
  89. }
  90. updateAndHandleResponse()
  91. }
  92. }, [sortData, biaotouModal])
  93. // 当拖拽和显示和隐藏后外部表格更新
  94. useEffect(() => {
  95. const storedHiddenColumns = localStorage.getItem('hiddenColumns1')
  96. if (storedHiddenColumns) {
  97. const hiddenColumns = JSON.parse(storedHiddenColumns)
  98. const updatedTableColumns = tableColumns.map(column => {
  99. if (
  100. hiddenColumns.find(
  101. item => item.name === column.key && item.is_show === false
  102. )
  103. ) {
  104. return { ...column, hidden: true }
  105. } else if (
  106. hiddenColumns.find(
  107. item => item.name === column.key && item.is_show === true
  108. )
  109. ) {
  110. return { ...column, hidden: false }
  111. }
  112. return column
  113. })
  114. setTableColumns(updatedTableColumns)
  115. }
  116. return () => {
  117. }
  118. }, [])

------------------------------------------------这是表头设置的table 和 外部的table 和 拖拽代码--------------
 

  1. // 表头设置里的table
  2. <DndContext
  3. modifiers={[restrictToVerticalAxis]}
  4. onDragEnd={onDragEnd}
  5. >
  6. <SortableContext
  7. items={biaotouData.map(i => i?.key)}
  8. strategy={verticalListSortingStrategy}
  9. >
  10. <SimpleBar
  11. style={{
  12. maxHeight: '600px',
  13. overflowY: 'auto',
  14. display: 'block'
  15. }}
  16. className='SimpleBar'
  17. >
  18. <Table
  19. columns={biaotouColumns}
  20. dataSource={biaotouData}
  21. loading={loading}
  22. pagination={false}
  23. components={{
  24. body: {
  25. row: Row1
  26. }
  27. }}
  28. rowKey='key'
  29. ></Table>
  30. </SimpleBar>
  31. </SortableContext>
  32. </DndContext>
  33. // 外部的table
  34. {TableCom2({ loading, data, columns: sortedColumns })}
  35. //被拖拽后
  36. const onDragEnd = ({ active, over }) => {
  37. console.log('active', active)
  38. if (active.id !== over?.id) {
  39. setBiaotouData(biaotouData => {
  40. const activeIndex = biaotouData.findIndex(
  41. item => item?.key === active.id
  42. )
  43. const overIndex = biaotouData.findIndex(item => item?.key === over?.id)
  44. const newData = arrayMove(biaotouData, activeIndex, overIndex).map(
  45. (item, index) => ({
  46. ...item,
  47. sort: index + 1
  48. })
  49. )
  50. // 创建一个新的映射以方便查找
  51. const keyToSortMap = newData.reduce((map, item) => {
  52. map[item.key] = item.sort
  53. return map
  54. }, {})
  55. console.log('keyToSortMap', keyToSortMap)
  56. // 遍历sortData,根据name查找对应的新Data中的sort值并赋值
  57. sortData.forEach(item => {
  58. if (item.name in keyToSortMap) {
  59. item.sort = keyToSortMap[item.name]
  60. }
  61. })
  62. // 遍历sortData,根据name查找对应的新Data中的sort值并赋值
  63. tableColumns.forEach(item => {
  64. if (item.key in keyToSortMap) {
  65. item.sort = keyToSortMap[item.key]
  66. }
  67. })
  68. setTableColumns(tableColumns)
  69. localStorage.setItem('hiddenColumns1', JSON.stringify(sortData))
  70. console.log('Updated sortData:', sortData)
  71. console.log('sortData', sortData)
  72. console.log('newData', newData)
  73. console.log('tableColumns', tableColumns)
  74. getEditMethod3({
  75. titleSetContent: JSON.stringify(sortData),
  76. type: 3
  77. })
  78. return arrayMove(biaotouData, activeIndex, overIndex)
  79. })
  80. }
  81. }
  82. //控制是否可以选中表格里的文字
  83. const Row1 = props => {
  84. const {
  85. attributes,
  86. listeners,
  87. setNodeRef,
  88. setActivatorNodeRef,
  89. transform,
  90. transition,
  91. isDragging
  92. } = useSortable({
  93. id: props['data-row-key']
  94. })
  95. const style = {
  96. ...props.style,
  97. transform: CSS.Translate.toString(transform),
  98. transition,
  99. ...(isDragging
  100. ? {
  101. position: 'relative',
  102. zIndex: 9999
  103. }
  104. : {})
  105. }
  106. const contextValue = useMemo(
  107. () => ({
  108. setActivatorNodeRef,
  109. listeners
  110. }),
  111. [setActivatorNodeRef, listeners]
  112. )
  113. return (
  114. <RowContext.Provider value={contextValue}>
  115. <tr {...props} ref={setNodeRef} style={style} {...attributes} />
  116. </RowContext.Provider>
  117. )
  118. }
  119. //拖拽图标
  120. const DragHandle = () => {
  121. const { setActivatorNodeRef, listeners } = useContext(RowContext)
  122. return (
  123. <Button
  124. type='text'
  125. size='small'
  126. icon={<HolderOutlined />}
  127. style={{
  128. cursor: 'move'
  129. }}
  130. ref={setActivatorNodeRef}
  131. {...listeners}
  132. />
  133. )
  134. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/733843
推荐阅读
相关标签
  

闽ICP备14008679号