写一段 JSX 并给出 Babel 编译后的 React.createElement 调用

解读

国内一线/二线前端面试中,这道题出现的频率极高,但“写一段 JSX”绝不是让你写 <h1>Hello</h1> 就完事。
面试官真正想看的是:

  1. 你是否理解 JSX 只是语法糖,最终会被 Babel 编译成 React.createElement(type, props, ...children);
  2. 你是否能正确写出“带自定义组件、条件渲染、列表 key、事件绑定、样式对象”等真实业务场景的 JSX;
  3. 你是否知道 Babel 7 默认使用 @babel/plugin-transform-react-jsx(classic 模式),以及 React 17+ 的 jsx-runtime 新入口,并能给出两种编译结果。

把这三点一次性展示清楚,就能拿到“熟悉 React 底层机制”的高分评价。

知识点

  • JSX 语法糖与 React.createElement 的映射规则
  • 组件首字母大写约定 vs 原生标签小写
  • 表达式嵌套 {}、条件 &&、三目、列表 map 与 key
  • 事件名 camelCase、样式对象、className 与 htmlFor
  • Babel classic 模式(React.createElement)与 automatic 模式(jsx-runtime)差异
  • children 被拍平(flatten)与 key 的编译位置

答案

下面给出一段“业务味”十足的 JSX,涵盖自定义组件、条件、列表、事件、样式、ref、Fragment,随后给出 Babel 7 classic 模式的编译产物。

JSX 源码(App.jsx)

import React, { useState, createRef } from 'react';

function TodoItem({ todo, onToggle }) {
  return (
    <li
      className={todo.done ? 'done' : ''}
      onClick={() => onToggle(todo.id)}
    >
      {todo.text}
    </li>
  );
}

export default function App() {
  const [list, setList] = useState([
    { id: 1, text: '复习 React', done: false },
    { id: 2, text: '手写 Fiber', done: true },
  ]);
  const inputRef = createRef();

  const add = () => {
    const text = inputRef.current.value.trim();
    if (!text) return;
    setList([...list, { id: Date.now(), text, done: false }]);
    inputRef.current.value = '';
  };

  const toggle = (id) =>
    setList(list.map((it) =>
      it.id === id ? { ...it, done: !it.done } : it
    ));

  return (
    <>
      <h1 style={{ textAlign: 'center' }}>待办清单</h1>
      <div>
        <input ref={inputRef} placeholder="请输入任务" />
        <button onClick={add}>添加</button>
      </div>
      {list.length === 0 ? (
        <p>暂无任务</p>
      ) : (
        <ul>
          {list.map((item) => (
            <TodoItem key={item.id} todo={item} onToggle={toggle} />
          ))}
        </ul>
      )}
    </>
  );
}

Babel 编译后(classic 模式,简化可读)

import React, { useState, createRef } from 'react';

function TodoItem({ todo, onToggle }) {
  return React.createElement(
    'li',
    {
      className: todo.done ? 'done' : '',
      onClick: () => onToggle(todo.id),
    },
    todo.text
  );
}

export default function App() {
  const [list, setList] = useState([
    { id: 1, text: '复习 React', done: false },
    { id: 2, text: '手写 Fiber', done: true },
  ]);
  const inputRef = createRef();

  const add = () => { /* 同上 */ };
  const toggle = (id) => { /* 同上 */ };

  return React.createElement(
    React.Fragment,
    null,
    React.createElement(
      'h1',
      { style: { textAlign: 'center' } },
      '待办清单'
    ),
    React.createElement(
      'div',
      null,
      React.createElement('input', { ref: inputRef, placeholder: '请输入任务' }),
      React.createElement('button', { onClick: add }, '添加')
    ),
    list.length === 0
      ? React.createElement('p', null, '暂无任务')
      : React.createElement(
          'ul',
          null,
          list.map((item) =>
            React.createElement(TodoItem, {
              key: item.id,
              todo: item,
              onToggle: toggle,
            })
          )
        )
  );
}

拓展思考

  1. React 17+ 的 jsx-runtime
    若项目配置 runtime: automatic,Babel 会生成
    import { jsx as _jsx } from 'react/jsx-runtime';
    然后调用 _jsx(type, props, key),不再显式引入 React。
    面试时可主动追问:“贵司是否已升级至新 JSX Transform?需要我给出 automatic 模式编译结果吗?”——体现你对工程化细节的关注。

  2. key 的编译位置
    在 classic 模式里,key 被提取到第三个参数:React.createElement(TodoItem, { todo: item, onToggle: toggle }, null, item.id);
    在 automatic 模式里,key 作为独立参数 _jsx(TodoItem, { ...props }, item.id)。

  3. 性能与可读性权衡
    手写 React.createElement 虽然能跑,但丧失 JSX 静态语法优势;
    了解编译产物后,可更合理地拆分组件、避免内联函数、减少 children 嵌套深度,从而减小打包体积与运行时开销。