feat(List): add ref on component (#50772)

Co-authored-by: Lansana DIOMANDE <lansana.diomande@cartier.comm>
This commit is contained in:
Lansana Diomande 2024-09-09 16:27:42 +02:00 committed by GitHub
parent 742ce37887
commit 9127cecc12
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 50 additions and 24 deletions

View File

@ -40,4 +40,14 @@ describe('List', () => {
expect(container.querySelector('.ant-list-sm')).toBeTruthy();
expect(container.querySelector('.ant-list-lg')).toBeTruthy();
});
it('ref should be able to get List id passe to internal div', async () => {
const renderItem: ListProps<any>['renderItem'] = (item) => <List.Item>{item}</List.Item>;
const dataSource: ListProps<any>['dataSource'] = [];
const ref = React.createRef<HTMLDivElement>();
const id = 'list-1';
render(<List ref={ref} id={id} renderItem={renderItem} dataSource={dataSource} />);
expect(ref.current?.id).toBe(id);
});
});

View File

@ -68,28 +68,31 @@ export interface ListLocale {
emptyText: React.ReactNode;
}
function List<T>({
pagination = false as ListProps<T>['pagination'],
prefixCls: customizePrefixCls,
bordered = false,
split = true,
className,
rootClassName,
style,
children,
itemLayout,
loadMore,
grid,
dataSource = [],
size: customizeSize,
header,
footer,
loading = false,
rowKey,
renderItem,
locale,
...rest
}: ListProps<T>) {
function InternalList<T>(
{
pagination = false as ListProps<T>['pagination'],
prefixCls: customizePrefixCls,
bordered = false,
split = true,
className,
rootClassName,
style,
children,
itemLayout,
loadMore,
grid,
dataSource = [],
size: customizeSize,
header,
footer,
loading = false,
rowKey,
renderItem,
locale,
...rest
}: ListProps<T>,
ref: React.ForwardedRef<HTMLDivElement>,
) {
const paginationObj = pagination && typeof pagination === 'object' ? pagination : {};
const [paginationCurrent, setPaginationCurrent] = React.useState(
@ -280,7 +283,7 @@ function List<T>({
return wrapCSSVar(
<ListContext.Provider value={contextValue}>
<div style={{ ...list?.style, ...style }} className={classString} {...rest}>
<div ref={ref} style={{ ...list?.style, ...style }} className={classString} {...rest}>
{(paginationPosition === 'top' || paginationPosition === 'both') && paginationContent}
{header && <div className={`${prefixCls}-header`}>{header}</div>}
<Spin {...loadingProp}>
@ -295,10 +298,23 @@ function List<T>({
);
}
const ListWithForwardRef = React.forwardRef(InternalList) as (<T>(
props: ListProps<T> & {
ref?: React.ForwardedRef<HTMLDivElement>;
},
) => ReturnType<typeof InternalList>) &
Pick<React.FC, 'displayName'>;
if (process.env.NODE_ENV !== 'production') {
List.displayName = 'List';
ListWithForwardRef.displayName = 'List';
}
type CompoundedComponent = typeof ListWithForwardRef & {
Item: typeof Item;
};
const List = ListWithForwardRef as CompoundedComponent;
List.Item = Item;
export default List;