Skip to content

Commit 3c499c1

Browse files
authored
feat: CSSMotionList support index in children (#49)
* feat: CSSMotionList support index in children * test: add test case
1 parent a687e24 commit 3c499c1

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

src/CSSMotionList.tsx

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ const MOTION_PROP_NAMES = [
3838
];
3939

4040
export interface CSSMotionListProps
41-
extends Omit<CSSMotionProps, 'onVisibleChanged'>,
41+
extends Omit<CSSMotionProps, 'onVisibleChanged' | 'children'>,
4242
Omit<React.HTMLAttributes<any>, 'children'> {
4343
keys: (React.Key | { key: React.Key; [name: string]: any })[];
4444
component?: string | React.ComponentType | false;
@@ -47,6 +47,16 @@ export interface CSSMotionListProps
4747
onVisibleChanged?: (visible: boolean, info: { key: React.Key }) => void;
4848
/** All motion leaves in the screen */
4949
onAllRemoved?: () => void;
50+
children?: (
51+
props: {
52+
visible?: boolean;
53+
className?: string;
54+
style?: React.CSSProperties;
55+
index?: number;
56+
[key: string]: any;
57+
},
58+
ref: (node: any) => void,
59+
) => React.ReactElement;
5060
}
5161

5262
export interface CSSMotionListState {
@@ -138,7 +148,7 @@ export function genCSSMotionList(
138148

139149
return (
140150
<Component {...restProps}>
141-
{keyEntities.map(({ status, ...eventProps }) => {
151+
{keyEntities.map(({ status, ...eventProps }, index) => {
142152
const visible = status === STATUS_ADD || status === STATUS_KEEP;
143153
return (
144154
<CSSMotion
@@ -158,7 +168,7 @@ export function genCSSMotionList(
158168
}
159169
}}
160170
>
161-
{children}
171+
{(props, ref) => children({ ...props, index }, ref)}
162172
</CSSMotion>
163173
);
164174
})}

tests/CSSMotionList.spec.tsx

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,4 +148,30 @@ describe('CSSMotionList', () => {
148148
expect(onVisibleChanged).toHaveBeenCalledWith(false, { key: 'a' });
149149
expect(onAllRemoved).toHaveBeenCalled();
150150
});
151+
152+
it('should support index', () => {
153+
const CSSMotionList = genCSSMotionList(false);
154+
155+
const Demo = ({ keys }) => (
156+
<CSSMotionList motionName="transition" keys={keys}>
157+
{({ key, style, className, index }) => (
158+
<div
159+
key={key}
160+
style={style}
161+
className={classNames('motion-box', className)}
162+
>
163+
{index}
164+
</div>
165+
)}
166+
</CSSMotionList>
167+
);
168+
169+
const { container } = render(<Demo keys={['a', 'b', 'c']} />);
170+
expect(container.querySelectorAll('.motion-box')[0].textContent).toEqual(
171+
'0',
172+
);
173+
expect(container.querySelectorAll('.motion-box')[1].textContent).toEqual(
174+
'1',
175+
);
176+
});
151177
});

0 commit comments

Comments
 (0)