Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(useVirtualList): mutate style in react context #2034

Merged
merged 6 commits into from
Feb 27, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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