Skip to content

Commit aae639a

Browse files
committed
feat(shared/hooks): 为 useChildrenWithRefs 的 cloneEl 添加 index 入参
1 parent 23a120a commit aae639a

File tree

2 files changed

+25
-14
lines changed

2 files changed

+25
-14
lines changed

packages/shared/src/hooks/__tests__/useChildrenWithRefs.test.tsx

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,13 +92,19 @@ describe('useChildrenWithRefs', () => {
9292
expect(obj.ref).toBe(firstChild);
9393
});
9494
test('cloneEl', () => {
95+
const arr: number[] = [];
9596
const App = () => {
96-
const [children] = useChildrenWithRefs(<div>foo</div>, (element, props) =>
97-
cloneElement(element, { ...props, className: 'foo' }),
97+
const [children] = useChildrenWithRefs(
98+
<div>foo</div>,
99+
(element, props, index) => {
100+
arr.push(index);
101+
return cloneElement(element, { ...props, className: 'foo' });
102+
},
98103
);
99104
return children;
100105
};
101106
const { container } = render(<App />);
102107
expect(container.firstChild).toHaveClass('foo');
108+
expect(arr).toEqual([0]);
103109
});
104110
});

packages/shared/src/hooks/useChildrenWithRefs.ts

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,25 +16,30 @@ export function useChildrenWithRefs(
1616
cloneEl?: (
1717
element: ReactElement<any, JSXElementConstructor<any> | string>,
1818
props: { ref: (el: HTMLElement) => void },
19+
index: number,
1920
) => ReactElement,
2021
): [children: ReactNode, refs: (HTMLElement | undefined)[]] {
2122
return useMemo(() => {
2223
const refs: (HTMLElement | undefined)[] = [];
23-
const clone = cloneEl || cloneElement;
24+
const clone = cloneEl || ((element, props) => cloneElement(element, props));
2425
const newChildren = Children.map(children, (child, index) => {
2526
if (!isValidElement(child)) return child;
26-
return clone(child, {
27-
ref: (el: HTMLElement) => {
28-
refs[index] = el;
29-
// ref 现在是直接放在 ReactElement 上的,props 虽然也有,但取的是 undefined
30-
const originRef = (child as any).ref;
31-
// const originRef = child.props.ref;
32-
if (!originRef) return;
33-
// 连通原来的 ref
34-
if (typeof originRef === 'function') originRef(el);
35-
else originRef.current = el;
27+
return clone(
28+
child,
29+
{
30+
ref: (el: HTMLElement) => {
31+
refs[index] = el;
32+
// ref 现在是直接放在 ReactElement 上的,props 虽然也有,但取的是 undefined
33+
const originRef = (child as any).ref;
34+
// const originRef = child.props.ref;
35+
if (!originRef) return;
36+
// 连通原来的 ref
37+
if (typeof originRef === 'function') originRef(el);
38+
else originRef.current = el;
39+
},
3640
},
37-
});
41+
index,
42+
);
3843
});
3944
return [newChildren, refs];
4045
}, [children]);

0 commit comments

Comments
 (0)