2024-02-24 14:50:03 +08:00
|
|
|
import React from 'react';
|
2024-02-20 14:02:43 +08:00
|
|
|
|
2023-07-05 16:54:04 +08:00
|
|
|
import type { AnyObject } from './type';
|
2019-04-24 12:21:02 +08:00
|
|
|
|
2022-10-20 16:37:35 +08:00
|
|
|
export function isFragment(child: any): boolean {
|
2024-02-24 14:50:03 +08:00
|
|
|
return child && React.isValidElement(child) && child.type === React.Fragment;
|
2022-08-16 09:59:27 +08:00
|
|
|
}
|
|
|
|
|
2024-06-22 21:59:12 +08:00
|
|
|
type RenderProps = AnyObject | ((originProps: AnyObject) => AnyObject | undefined);
|
2020-11-17 23:03:07 +08:00
|
|
|
|
2024-02-24 15:51:51 +08:00
|
|
|
export const replaceElement = <P>(
|
2020-05-14 20:54:49 +08:00
|
|
|
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;
|
|
|
|
}
|
2024-02-20 14:02:43 +08:00
|
|
|
return React.cloneElement<P>(
|
2020-11-21 19:00:11 +08:00
|
|
|
element,
|
|
|
|
typeof props === 'function' ? props(element.props || {}) : props,
|
|
|
|
);
|
2024-02-24 15:51:51 +08:00
|
|
|
};
|
2020-05-14 20:54:49 +08:00
|
|
|
|
2024-02-20 14:02:43 +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
|
|
|
}
|