示例工程 29-jsx-react-types
29-jsx-react-types/03-generic-component/src/react-like.ts
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
export type ReactNode = string | number | null | undefined | ReactElement | readonly ReactNode[];
export interface ReactElement {
type: unknown;
props: Record<string, unknown>;
children: ReactNode[];
}
export function h(
type: unknown,
props: Record<string, unknown> | null,
...children: ReactNode[]
): ReactElement {
return { type, props: props ?? {}, children };
}
export function render(node: ReactNode): string {
if (node === null || node === undefined || typeof node === 'boolean') return '';
if (typeof node === 'string' || typeof node === 'number') return String(node);
if (Array.isArray(node)) return node.map(render).join('');
const element = node as ReactElement;
if (typeof element.type === 'function') {
return render((element.type as (props: Record<string, unknown>) => ReactElement)(element.props));
}
return `<${String(element.type)}>${element.children.map(render).join('')}</${String(element.type)}>`;
}
declare global {
namespace JSX {
interface Element extends ReactElement {}
interface ElementChildrenAttribute {
children: {};
}
interface IntrinsicElements {
ul: { children?: ReactNode };
li: { children?: ReactNode };
span: { children?: ReactNode };
}
}
}