Skip to content

Commit 2f17dce

Browse files
committed
feat(shared/utils): 新增 forwardRefs
1 parent dfab3fb commit 2f17dce

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { renderHook } from '@testing-library/react';
2+
import { forwardRefs } from '../';
3+
import { useRef } from 'react';
4+
5+
describe('forwardRefs', () => {
6+
test('forwardRefs should work', () => {
7+
const ref2 = jest.fn();
8+
const hook = renderHook(() => {
9+
const ref1 = useRef();
10+
forwardRefs(100, ref1, ref2);
11+
return ref1.current;
12+
});
13+
expect(hook.result.current).toBe(100);
14+
expect(ref2.mock.calls[0][0]).toBe(100);
15+
});
16+
});
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import type { MutableRefObject, Ref } from 'react';
2+
3+
/**
4+
* 传递 ref
5+
*/
6+
export function forwardRefs(
7+
value: unknown,
8+
...refs: (Ref<unknown> | undefined)[]
9+
): void {
10+
refs.forEach((ref): void => {
11+
if (!ref) return;
12+
switch (typeof ref) {
13+
case 'function':
14+
ref(value);
15+
break;
16+
case 'object':
17+
(ref as MutableRefObject<unknown>).current = value;
18+
break;
19+
}
20+
});
21+
}

packages/shared/src/utils/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ export * from './getElRealSize';
44
export * from './getSizeClassName';
55
export * from './getClasses';
66
export * from './isSameReactEl';
7+
export * from './forwardRefs';

0 commit comments

Comments
 (0)