示例工程 29-jsx-react-types

29-jsx-react-types/04-discriminated-props/src/main.tsx

tsx · 1.0 KB

运行:29 · discriminated-props

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

import { h, render } from './react-like.js';
import type { ReactElement } from './react-like.js';
 
type AlertProps =
  | { kind: 'error'; message: string }
  | { kind: 'success' };
 
function Alert(props: AlertProps): ReactElement {
  const text = props.kind === 'error' ? props.message : 'ok';
  return <div className={props.kind}>{text}</div>;
}
 
interface Counter {
  count: number;
  inc(): number;
}
 
// 以普通函数模拟 hook 的类型形态(不依赖 React 运行时)
export function useCounter(initial: number): Counter {
  let count = initial;
  return {
    get count() {
      return count;
    },
    inc() {
      count += 1;
      return count;
    },
  };
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  const counter = useCounter(0);
  counter.inc();
  const lines = [
    render(<Alert kind="error" message={`failed:${counter.count}`} />),
    render(<Alert kind="success" />),
  ];
  for (const line of lines) {
    log(line);
  }
  return lines;
}