lijianan
2 years ago
committed by
GitHub
28 changed files with 178 additions and 182 deletions
@ -1,16 +0,0 @@ |
|||
import React from 'react'; |
|||
import type { SizeType } from '../../config-provider/SizeContext'; |
|||
import SizeContext from '../../config-provider/SizeContext'; |
|||
|
|||
const useSize = <T extends string>(customizeSize?: T) => { |
|||
const size = React.useContext<SizeType>(SizeContext); |
|||
const mergeSize = React.useMemo<T>(() => { |
|||
if (!customizeSize) { |
|||
return size as T; |
|||
} |
|||
return customizeSize ?? size; |
|||
}, [customizeSize, size]); |
|||
return mergeSize; |
|||
}; |
|||
|
|||
export default useSize; |
@ -0,0 +1,17 @@ |
|||
import React from 'react'; |
|||
import { render } from '../../../tests/utils'; |
|||
import useSize from '../hooks/useSize'; |
|||
|
|||
describe('useSize', () => { |
|||
it('useSize', () => { |
|||
const Demo: React.FC<{ size?: any }> = ({ size }) => <div>{useSize(size)}</div>; |
|||
const { container, rerender } = render(<Demo />); |
|||
expect(container.querySelector<HTMLDivElement>('div')?.textContent).toBe(''); |
|||
rerender(<Demo size="test-size1" />); |
|||
expect(container.querySelector<HTMLDivElement>('div')?.textContent).toBe('test-size1'); |
|||
rerender(<Demo size={() => 'test-size2'} />); |
|||
expect(container.querySelector<HTMLDivElement>('div')?.textContent).toBe('test-size2'); |
|||
rerender(<Demo size={1} />); |
|||
expect(container.querySelector<HTMLDivElement>('div')?.textContent).toBe(''); |
|||
}); |
|||
}); |
@ -0,0 +1,22 @@ |
|||
import React from 'react'; |
|||
import type { SizeType } from '../SizeContext'; |
|||
import SizeContext from '../SizeContext'; |
|||
|
|||
const useSize = <T>(customSize?: T | ((ctxSize: SizeType) => T)): T => { |
|||
const size = React.useContext<SizeType>(SizeContext); |
|||
const mergedSize = React.useMemo<T>(() => { |
|||
if (!customSize) { |
|||
return size as T; |
|||
} |
|||
if (typeof customSize === 'string') { |
|||
return customSize ?? size; |
|||
} |
|||
if (customSize instanceof Function) { |
|||
return customSize(size); |
|||
} |
|||
return size as T; |
|||
}, [customSize, size]); |
|||
return mergedSize; |
|||
}; |
|||
|
|||
export default useSize; |
Loading…
Reference in new issue