Skip to content

Commit

Permalink
fix(useVirtualList): mutate style in react context (#2034)
Browse files Browse the repository at this point in the history
Co-authored-by: 潇见 <xiaojian.lj@antgroup.com>
  • Loading branch information
luo3house and crazylxr authored Feb 27, 2023
1 parent e7682c1 commit 29c9203
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions packages/hooks/src/useVirtualList/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { useEffect, useMemo, useState, useRef } from 'react';
import { useEffect, useMemo, useState, useRef, CSSProperties } from 'react';
import useEventListener from '../useEventListener';
import useLatest from '../useLatest';
import useMemoizedFn from '../useMemoizedFn';
import useSize from '../useSize';
import { getTargetElement } from '../utils/domTarget';
import type { BasicTarget } from '../utils/domTarget';
import { isNumber } from '../utils';
import useUpdateEffect from '../useUpdateEffect';

type ItemHeight<T> = (index: number, data: T) => number;

Expand All @@ -27,6 +28,8 @@ const useVirtualList = <T = any>(list: T[], options: Options<T>) => {

const [targetList, setTargetList] = useState<{ index: number; data: T }[]>([]);

const [wrapperStyle, setWrapperStyle] = useState<CSSProperties>({});

const getVisibleCount = (containerHeight: number, fromIndex: number) => {
if (isNumber(itemHeightRef.current)) {
return Math.ceil(containerHeight / itemHeightRef.current);
Expand Down Expand Up @@ -86,9 +89,8 @@ const useVirtualList = <T = any>(list: T[], options: Options<T>) => {

const calculateRange = () => {
const container = getTargetElement(containerTarget);
const wrapper = getTargetElement(wrapperTarget) as HTMLElement;

if (container && wrapper) {
if (container) {
const { scrollTop, clientHeight } = container;

const offset = getOffset(scrollTop);
Expand All @@ -99,8 +101,10 @@ const useVirtualList = <T = any>(list: T[], options: Options<T>) => {

const offsetTop = getDistanceTop(start);

wrapper.style.height = totalHeight - offsetTop + 'px';
wrapper.style.marginTop = offsetTop + 'px';
setWrapperStyle({
height: totalHeight - offsetTop + 'px',
marginTop: offsetTop + 'px',
});

setTargetList(
list.slice(start, end).map((ele, index) => ({
Expand All @@ -111,6 +115,13 @@ const useVirtualList = <T = any>(list: T[], options: Options<T>) => {
}
};

useUpdateEffect(() => {
const wrapper = getTargetElement(wrapperTarget) as HTMLElement;
if (wrapper) {
Object.keys(wrapperStyle).forEach((key) => (wrapper.style[key] = wrapperStyle[key]));
}
}, [wrapperStyle]);

useEffect(() => {
if (!size?.width || !size?.height) {
return;
Expand Down

0 comments on commit 29c9203

Please sign in to comment.