Skip to main content

React.createElement

测试jsx编译

在src/index.js文件中

const App = (
<div>test</div>
)

console.log(App)

index.js:6 Uncaught ReferenceError: React is not defined at index.js:6:5 at main.js:9:12

从前文我们知道,我们需要创建一个React对象,并且包含一个createElement方法

把我们写的jsx代码放到babel上解析

解析前

<div id="test">test</div>

解析后

React.createElement("div", {
id: "test"
}, "test");

创建react库

创建react文件夹以及index.js文件

const React = {
createElement
}

function createElement() {

}

export default React

根据babel解析的结果,我们知道createElement需要几个参数

  • tag
  • attributes
  • child1
  • child2
  • other child

所以我们这么写createElement方法

const React = {
createElement
}

function createElement(tag, attributes, ...children) {
return {
tag,
attributes,
children
}
}

export default React

我们把jsx的解析结果组合成一个js对象,即虚拟dom

在代码中使用我们的react

import React from './react'

保存之后,在控制台就能看到正确的输出

App jsx解析之后的虚拟dom

{
"tag": "div",
"attributes": null,
"children": [
"test"
]
}