示例工程 29-jsx-react-types

29-jsx-react-types/01-hello-jsx/src/react-like.ts

typescript · 1.6 KB

运行:29 · hello-jsx

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

// 最小 React-like 类型层:只验证 JSX 类型与运行时渲染,不依赖 React
export type ReactNode =
  | string
  | number
  | boolean
  | null
  | undefined
  | ReactElement
  | readonly ReactNode[];
 
export interface ReactElement {
  type: unknown;
  props: Record<string, unknown>;
  children: ReactNode[];
}
 
export type Component<P> = (props: P) => ReactElement;
 
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;
  const component = element.type as Component<Record<string, unknown>>;
  if (typeof element.type === 'function') {
    return render(component(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 {
      div: { id?: string; className?: string; children?: ReactNode };
      span: { children?: ReactNode };
      button: { disabled?: boolean; children?: ReactNode };
    }
  }
}