Преглед изворни кода

fix: 修改useTableScroll导出的redoHeight在table的调用时机

lanjianrong пре 5 година
родитељ
комит
b47feb6c42
3 измењених фајлова са 204 додато и 208 уклоњено
  1. 148 147
      src/hooks/useAutoTable.js
  2. 4 1
      src/pages/Customer/Company/index.jsx
  3. 52 60
      src/pages/Customer/Contact/index.jsx

+ 148 - 147
src/hooks/useAutoTable.js

@@ -1,147 +1,148 @@
-import { useState, useEffect, useMemo, useLayoutEffect, useRef } from 'react'
-import { useDebounceFn, useMount, useUpdateLayoutEffect } from 'ahooks'
-import { useStore } from 'dva'
-import { getViewportOffset } from '@/utils/domUtils'
-import { useWindowSizeFn } from './event/useWindomSizeFn'
-/**
- * @param {number} needSubtractHeight 被裁去的高度
- * @param {number} needSubtractWidth 被裁去的宽度
- */
-const useAutoTable = (needSubtractHeight, needSubtractWidth) => {
-  const { collapsed = true } = useStore().getState().global
-  const [scroll, setScroll] = useState({
-    x: document.body.clientWidth - ((collapsed ? 208 : 48) + needSubtractWidth),
-    y: document.body.clientHeight - needSubtractHeight
-  })
-  // const { run, cancel } = useDebounceFn(handleScroll, { wait: 5000})
-  const { run, cancel } = useDebounceFn(() =>
-    setScroll({
-      ...scroll,
-      x: document.body.clientWidth - ((collapsed ? 208 : 48) + needSubtractWidth),
-      y: document.body.clientHeight - needSubtractHeight
-    })
-  )
-  useEffect(() => {
-    run()
-    return () => cancel()
-  }, [collapsed])
-  useEffect(() => {
-    window.addEventListener('resize', run)
-    return () => {
-      window.removeEventListener('resize', cancel)
-    }
-  }, [])
-
-  // 实际返回的宽度要大一点让table出现滚动条,反正折叠菜单栏卡顿
-  return [scroll.x + 50, scroll.y]
-}
-
-export default useAutoTable
-
-export function useTableScroll(columnsRef, selectKeysRef) {
-  let paginationEl = null
-  let footerEl = null
-  let bodyEl = null
-  const [tableHeight, setTableHeight] = useState(null)
-
-  async function calcTableHeight() {
-    const tableEl = document.getElementsByClassName('ant-table-wrapper')[0]
-    if (!tableEl) return
-    if (!bodyEl) {
-      bodyEl = tableEl.querySelector('.ant-table-body')
-      bodyEl && (bodyEl.style.height = 'unset')
-    }
-    // Add a delay to get the correct bottomIncludeBody paginationHeight footerHeight headerHeight
-
-    const headEl = tableEl.querySelector('.ant-table-thead ')
-
-    if (!headEl) return
-    // Table height from bottom
-    const { bottomIncludeBody } = getViewportOffset(headEl)
-
-    const paddingHeight = 64
-
-    let paginationHeight = 2
-
-    if (!paginationEl) {
-      paginationEl = tableEl.querySelector('.ant-pagination')
-      if (paginationEl) {
-        const { offsetHeight } = paginationEl
-        paginationHeight += offsetHeight || 0
-      } else {
-        // TODO First fix 24
-        paginationHeight += 24
-      }
-    } else {
-      paginationHeight = -8
-    }
-
-    let footerHeight = 0
-    if (!paginationEl) {
-      if (!footerEl) {
-        footerEl = tableEl.querySelector('.ant-table-footer')
-      } else {
-        const { offsetHeight } = footerEl
-        footerHeight += offsetHeight || 0
-      }
-    }
-
-    let headerHeight = 0
-    if (headEl) {
-      headerHeight = headEl.offsetHeight
-    }
-
-    const height =
-      bottomIncludeBody - paddingHeight - paginationHeight - footerHeight - headerHeight
-    setTableHeight(height)
-    bodyEl && (bodyEl.style.height = `${height}px`)
-  }
-
-  function redoHeight() {
-    calcTableHeight()
-  }
-  const { run: debounceRedoHeight } = useDebounceFn(redoHeight, { wait: 280 })
-
-  // Greater than animation time 280
-  useWindowSizeFn(calcTableHeight, 280)
-
-  useMount(() => {
-    debounceRedoHeight()
-  })
-
-  useUpdateLayoutEffect(() => {
-    debounceRedoHeight()
-  }, [selectKeysRef.length])
-
-  const getSrollX = useMemo(() => {
-    let width = 0
-    if (selectKeysRef.length) {
-      width += 60
-    }
-
-    // TODO props ?? 0;
-    const NORMAL_WIDTH = 150
-
-    const columns = columnsRef.filter(item => !item.defaultHidden)
-    columns.forEach(item => {
-      width += Number.parseInt(item.width) || 0
-    })
-
-    const unsetWidthColumns = columns.filter(item => !Reflect.has(item, 'width'))
-
-    const len = unsetWidthColumns.length
-    if (len !== 0) {
-      width += len * NORMAL_WIDTH
-    }
-    const tableEl = document.getElementsByClassName('ant-pro-table')[0]
-
-    const tableWidth = tableEl && tableEl.offsetWidth ? tableEl.offsetWidth : 0
-
-    return tableWidth > width ? '100%' : width
-  }, [selectKeysRef])
-
-  const getScrollRef = useMemo(() => {
-    return { x: getSrollX, y: tableHeight || null }
-  }, [getSrollX, tableHeight])
-  return { getScrollRef, redoHeight }
-}
+import { useState, useEffect, useMemo } from 'react'
+import { useDebounceFn, useMount, useUpdateLayoutEffect } from 'ahooks'
+import { useStore } from 'dva'
+import { getViewportOffset } from '@/utils/domUtils'
+import { useWindowSizeFn } from './event/useWindomSizeFn'
+/**
+ * @param {number} needSubtractHeight 被裁去的高度
+ * @param {number} needSubtractWidth 被裁去的宽度
+ */
+const useAutoTable = (needSubtractHeight, needSubtractWidth) => {
+  const { collapsed = true } = useStore().getState().global
+  const [scroll, setScroll] = useState({
+    x: document.body.clientWidth - ((collapsed ? 208 : 48) + needSubtractWidth),
+    y: document.body.clientHeight - needSubtractHeight
+  })
+  // const { run, cancel } = useDebounceFn(handleScroll, { wait: 5000})
+  const { run, cancel } = useDebounceFn(() =>
+    setScroll({
+      ...scroll,
+      x: document.body.clientWidth - ((collapsed ? 208 : 48) + needSubtractWidth),
+      y: document.body.clientHeight - needSubtractHeight
+    })
+  )
+  useEffect(() => {
+    run()
+    return () => cancel()
+  }, [collapsed])
+  useEffect(() => {
+    window.addEventListener('resize', run)
+    return () => {
+      window.removeEventListener('resize', cancel)
+    }
+  }, [])
+
+  // 实际返回的宽度要大一点让table出现滚动条,反正折叠菜单栏卡顿
+  return [scroll.x + 50, scroll.y]
+}
+
+export default useAutoTable
+
+export function useTableScroll(columnsRef, selectKeysRef) {
+  let paginationEl = null
+  let footerEl = null
+  let bodyEl = null
+  const [tableHeight, setTableHeight] = useState(null)
+
+  async function calcTableHeight() {
+    const tableEl = document.getElementsByClassName('ant-table-container')[0]
+    if (!tableEl) return
+    if (!bodyEl) {
+      bodyEl = tableEl.querySelector('.ant-table-body')
+      bodyEl && (bodyEl.style.height = 'unset')
+    }
+    // Add a delay to get the correct bottomIncludeBody paginationHeight footerHeight headerHeight
+
+    const headEl = tableEl.querySelector('.ant-table-thead ')
+
+    if (!headEl) return
+    // Table height from bottom
+    const { bottomIncludeBody } = getViewportOffset(headEl)
+    //
+    const paddingHeight = 24
+
+    let paginationHeight = 32
+
+    if (!paginationEl) {
+      paginationEl = tableEl.querySelector('.ant-pagination')
+      if (paginationEl) {
+        const { offsetHeight } = paginationEl
+        paginationHeight += offsetHeight || 0
+      } else {
+        // TODO First fix 24
+        paginationHeight += 24
+      }
+    } else {
+      paginationHeight = -32
+    }
+
+    let footerHeight = 0
+    if (!paginationEl) {
+      if (!footerEl) {
+        footerEl = tableEl.querySelector('.ant-table-footer')
+      } else {
+        const { offsetHeight } = footerEl
+        footerHeight += offsetHeight || 0
+      }
+    }
+
+    let headerHeight = 0
+    if (headEl) {
+      headerHeight = headEl.offsetHeight
+    }
+
+    const height =
+      bottomIncludeBody - paddingHeight - paginationHeight - footerHeight - headerHeight
+    setTableHeight(height)
+    bodyEl && (bodyEl.style.height = `${height}px`)
+  }
+
+  function redoHeight() {
+    calcTableHeight()
+  }
+  const { run: debounceRedoHeight } = useDebounceFn(redoHeight, { wait: 280 })
+
+  // Greater than animation time 280
+  useWindowSizeFn(calcTableHeight, 280)
+
+  useMount(() => {
+    debounceRedoHeight()
+  })
+
+  useUpdateLayoutEffect(() => {
+    debounceRedoHeight()
+  }, [selectKeysRef.length])
+
+  const getSrollX = useMemo(() => {
+    let width = 0
+    if (selectKeysRef.length) {
+      width += 60
+    }
+
+    // TODO props ?? 0;
+    const NORMAL_WIDTH = 150
+
+    const columns = columnsRef.filter(item => !item.defaultHidden)
+    columns.forEach(item => {
+      // eslint-disable-next-line radix
+      width += Number.parseInt(item.width) || 0
+    })
+
+    const unsetWidthColumns = columns.filter(item => !Reflect.has(item, 'width'))
+
+    const len = unsetWidthColumns.length
+    if (len !== 0) {
+      width += len * NORMAL_WIDTH
+    }
+    const tableEl = document.getElementsByClassName('ant-pro-table')[0]
+
+    const tableWidth = tableEl && tableEl.offsetWidth ? tableEl.offsetWidth : 0
+
+    return tableWidth > width ? '100%' : width
+  }, [selectKeysRef])
+
+  const getScrollRef = useMemo(() => {
+    return { x: getSrollX, y: tableHeight || null }
+  }, [getSrollX, tableHeight])
+  return { getScrollRef, redoHeight }
+}

+ 4 - 1
src/pages/Customer/Company/index.jsx

@@ -340,7 +340,7 @@ const Company = props => {
     setTagState({ ...tagState, [type]: ids })
     setTagState({ ...tagState, [type]: ids })
   }
   }
 
 
-  const { getScrollRef } = useTableScroll(columns, selectKeys)
+  const { getScrollRef, redoHeight } = useTableScroll(columns, selectKeys)
 
 
   // 批量设置-确认触发
   // 批量设置-确认触发
   const tagsSettingConfirm = async clientIds => {
   const tagsSettingConfirm = async clientIds => {
@@ -466,6 +466,9 @@ const Company = props => {
         type: 'checkbox',
         type: 'checkbox',
         columnWidth: 25
         columnWidth: 25
       }}
       }}
+      onLoadingChange={loadingStatus => {
+        loadingStatus && redoHeight()
+      }}
       tableAlertRender={renderTableAlert}
       tableAlertRender={renderTableAlert}
       scroll={getScrollRef}
       scroll={getScrollRef}
       columnsStateMap={columnsStateMap}
       columnsStateMap={columnsStateMap}

+ 52 - 60
src/pages/Customer/Contact/index.jsx

@@ -434,7 +434,7 @@ const Contact = props => {
     }
     }
   })
   })
 
 
-  const { getScrollRef } = useTableScroll(columns, selectKeys)
+  const { getScrollRef, redoHeight } = useTableScroll(columns, selectKeys)
 
 
   // 默认刷新一次列表请求数据
   // 默认刷新一次列表请求数据
   useEffect(() => {
   useEffect(() => {
@@ -562,65 +562,57 @@ const Contact = props => {
     )
     )
   }
   }
   return (
   return (
-    <div>
-      <ProTable
-        bordered
-        params={state.params}
-        actionRef={tRef}
-        rowKey={record => record.id}
-        columns={columns}
-        request={async (params, sort, filter) => {
-          const {
-            code = -1,
-            data: { client = [], total = 0 }
-          } = await queryContact({ ...params, ...sort, ...filter })
-          setState({ ...state, orderIds: client.map(item => item.id) })
-          return {
-            data: client,
-            success: code === consts.RET_CODE.SUCCESS,
-            total
-          }
-        }}
-        // summary={() => (
-        //   <ProTable.Summary.Row>
-        //     <ProTable.Summary.Cell>统计: 总数</ProTable.Summary.Cell>
-        //     <ProTable.Summary.Cell />
-        //     <ProTable.Summary.Cell>未填写: {state.tail.department}</ProTable.Summary.Cell>
-        //     <ProTable.Summary.Cell>未填写: {state.tail.telephone}</ProTable.Summary.Cell>
-        //     <ProTable.Summary.Cell>未填写: {state.tail.email}</ProTable.Summary.Cell>
-        //   </ProTable.Summary.Row>
-        // )}
-        tableAlertRender={renderTableAlert}
-        rowSelection={{
-          onChange: hanleRowSelectChange,
-          type: 'checkbox',
-          columnWidth: 25
-        }}
-        // search={false}
-        search={{ filterType: 'light' }}
-        toolbar={{
-          search: {
-            allowClear: true,
-            onSearch: handleSearch,
-            placeholder: '输入联系人、客户名称、电话邮箱等'
-          },
-          actions: [
-            <LazyCascader
-              key="lazyCascader"
-              onChange={onDistrictChange}
-              changeOnSelect={true}
-              bordered={false}
-              className="hover:bg-[rgba(0,0,0,0.1)]"
-            />,
-            <Addcontact onConfirm={handleAddClient} key="addContactBtn" />
-          ]
-        }}
-        scroll={getScrollRef}
-        columnsStateMap={columnsStateMap}
-        onColumnsStateChange={map => setColumnsStateMap(map)}
-        headerTitle="联系人"
-      />
-    </div>
+    <ProTable
+      bordered
+      params={state.params}
+      actionRef={tRef}
+      rowKey={record => record.id}
+      columns={columns}
+      request={async (params, sort, filter) => {
+        const {
+          code = -1,
+          data: { client = [], total = 0 }
+        } = await queryContact({ ...params, ...sort, ...filter })
+        setState({ ...state, orderIds: client.map(item => item.id) })
+        return {
+          data: client,
+          success: code === consts.RET_CODE.SUCCESS,
+          total
+        }
+      }}
+      tableAlertRender={renderTableAlert}
+      rowSelection={{
+        onChange: hanleRowSelectChange,
+        type: 'checkbox',
+        columnWidth: 25
+      }}
+      // search={false}
+      search={{ filterType: 'light' }}
+      toolbar={{
+        search: {
+          allowClear: true,
+          onSearch: handleSearch,
+          placeholder: '输入联系人、客户名称、电话邮箱等'
+        },
+        actions: [
+          <LazyCascader
+            key="lazyCascader"
+            onChange={onDistrictChange}
+            changeOnSelect={true}
+            bordered={false}
+            className="hover:bg-[rgba(0,0,0,0.1)]"
+          />,
+          <Addcontact onConfirm={handleAddClient} key="addContactBtn" />
+        ]
+      }}
+      onLoadingChange={loadingStatus => {
+        loadingStatus && redoHeight()
+      }}
+      scroll={getScrollRef}
+      columnsStateMap={columnsStateMap}
+      onColumnsStateChange={map => setColumnsStateMap(map)}
+      headerTitle="联系人"
+    />
   )
   )
 }
 }