示例工程 29-jsx-react-types

29-jsx-react-types/02-intrinsic-elements/src/react-like.ts

typescript · 1.6 KB

运行:29 · intrinsic-elements

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// 最小 JSX shim:只覆盖本示例用到的标签与属性
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));
  }
  const attributes = Object.entries(element.props)
    .filter(([key]) => key !== 'children')
    .map(([key, value]) => ` ${key}="${String(value)}"`)
    .join('');
  return `<${String(element.type)}${attributes}>${element.children.map(render).join('')}</${String(element.type)}>`;
}
 
declare global {
  namespace JSX {
    interface Element extends ReactElement {}
    interface ElementChildrenAttribute {
      children: {};
    }
    interface IntrinsicElements {
      a: { href: string; target?: string; children?: ReactNode };
      img: { src: string; alt: string; width?: number };
      input: { type?: string; value?: string; disabled?: boolean };
      form: { action?: string; children?: ReactNode };
    }
  }
}