Skip to content

Commit abd79c6

Browse files
committed
feat(shared): 新增 mergeReactDefaultProps 工具函数
1 parent c75fa57 commit abd79c6

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { render } from '@testing-library/react';
2+
import { mergeReactDefaultProps } from '../';
3+
import React from 'react';
4+
5+
describe('mergeReactDefaultProps', () => {
6+
test('base', () => {
7+
const receiveProps = jest.fn();
8+
const defaultProps = {
9+
emptyStr: 5,
10+
undef: 1,
11+
null: 2,
12+
zero: 4,
13+
nan: 3,
14+
};
15+
const App: React.FC<any> = React.forwardRef<HTMLDivElement, any>(
16+
(props: any, ref) => {
17+
receiveProps(props);
18+
return <div ref={ref}>1</div>;
19+
},
20+
);
21+
App.defaultProps = defaultProps;
22+
const props = {
23+
undef: undefined,
24+
emptyStr: '',
25+
null: null,
26+
nan: NaN,
27+
zero: 0,
28+
};
29+
render(<App {...props} />);
30+
const result = {
31+
emptyStr: '',
32+
null: null,
33+
nan: NaN,
34+
undef: 1,
35+
zero: 0,
36+
};
37+
expect(receiveProps.mock.calls[0]).toEqual([result]);
38+
39+
expect(mergeReactDefaultProps(props, defaultProps as any)).toEqual(result);
40+
});
41+
});

packages/shared/src/utils/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@ export * from './getSizeClassName';
55
export * from './getClasses';
66
export * from './isSameReactEl';
77
export * from './forwardRefs';
8+
export * from './mergeReactDefaultProps';
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { RequiredPart } from '@tool-pack/types';
2+
import { defaults } from '@tool-pack/basic';
3+
4+
/**
5+
* 用于代替 react 的 defaultProps 合并功能
6+
*/
7+
export function mergeReactDefaultProps<const T, const P>(
8+
props: T,
9+
defaultProps: P,
10+
): keyof P extends keyof T ? RequiredPart<T, keyof P> : T & P {
11+
return defaults({ ...props }, defaultProps) as any;
12+
}

0 commit comments

Comments
 (0)