ant-design/components/_util/reactNode.ts

28 lines
761 B
TypeScript
Raw Normal View History

2024-02-24 14:50:03 +08:00
import React from 'react';
import type { AnyObject } from './type';
export function isFragment(child: any): boolean {
2024-02-24 14:50:03 +08:00
return child && React.isValidElement(child) && child.type === React.Fragment;
}
2022-09-09 10:03:49 +08:00
type RenderProps = AnyObject | ((originProps: AnyObject) => AnyObject | void);
2024-02-24 15:51:51 +08:00
export const replaceElement = <P>(
element: React.ReactNode,
replacement: React.ReactNode,
2022-09-09 10:03:49 +08:00
props?: RenderProps,
2024-02-24 15:51:51 +08:00
) => {
if (!React.isValidElement<P>(element)) {
2022-09-09 10:03:49 +08:00
return replacement;
}
return React.cloneElement<P>(
element,
typeof props === 'function' ? props(element.props || {}) : props,
);
2024-02-24 15:51:51 +08:00
};
export function cloneElement<P>(element: React.ReactNode, props?: RenderProps) {
return replaceElement<P>(element, element, props) as React.ReactElement;
2019-05-07 14:57:32 +08:00
}