Skip to content

Commit

Permalink
feat(scroll-view): add props itemKey to specify keys for items
Browse files Browse the repository at this point in the history
  • Loading branch information
akai committed Dec 2, 2020
1 parent 646cbb5 commit 5de57ca
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/components/ScrollView/ScrollView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ import { IconButton } from '../IconButton';
import canUse from '../../utils/canUse';

export type ScrollViewProps<T> = Pick<ScrollViewItemProps, 'effect' | 'onIntersect'> & {
data: Array<T>;
renderItem: (item: T, index: number) => React.ReactNode;
className?: string;
fullWidth?: boolean;
scrollX?: boolean;
data: Array<T>;
renderItem: (item: T, index: number) => React.ReactNode;
itemKey?: string | ((item: T, index: number) => string);
onScroll?: (event: React.UIEvent<HTMLDivElement, UIEvent>) => void;
children?: React.ReactNode;
};
Expand All @@ -27,6 +28,7 @@ export const ScrollView = React.forwardRef<ScrollViewHandle, ScrollViewProps<any
scrollX = true,
effect = 'slide',
data,
itemKey,
renderItem,
onIntersect,
onScroll,
Expand All @@ -46,6 +48,14 @@ export const ScrollView = React.forwardRef<ScrollViewHandle, ScrollViewProps<any
el.scrollLeft += el.offsetWidth;
}

function getItemKey(item: any, index: number) {
let key;
if (itemKey) {
key = typeof itemKey === 'function' ? itemKey(item, index) : item[itemKey];
}
return key || index;
}

useImperativeHandle(ref, () => ({
scrollTo: ({ x, y }: { x?: number; y?: number }) => {
if (x != null) {
Expand Down Expand Up @@ -77,7 +87,7 @@ export const ScrollView = React.forwardRef<ScrollViewHandle, ScrollViewProps<any
<div className="ScrollView-scroller" ref={scrollerRef} onScroll={onScroll}>
<div className="ScrollView-inner">
{data.map((item, i) => (
<Item item={item} effect={effect} onIntersect={onIntersect} key={i}>
<Item item={item} effect={effect} onIntersect={onIntersect} key={getItemKey(item, i)}>
{renderItem(item, i)}
</Item>
))}
Expand Down

0 comments on commit 5de57ca

Please sign in to comment.