跳到主要内容

React 中 JSX 的本质

JSX 本质

  • JSX 等同于 Vue 模板
  • Vue 模板不是 html
  • JSX 也不是 JS

Vue 模板编译

// 插值
const template = `<p>{{message}}</p>`
// with(this){return createElement('p',[createTextVNode(toString(message))])}

JSX 编译

可以在 https://babeljs.io/repl 测试,记得勾选 PRESETS->react

jsx 代码

// JSX 基本用法
const imgElem = <div id="div1">
<p>some text</p>
<img src={imgUrl}/>
</div>

// JSX style
const styleData = { fontSize: '30px', color: 'blue' }
const styleElem = <p style={styleData}>设置 style</p>

// JSX 加载组件
const app = <div>
<Input submitTitle={onSubmitTitle}/>
<List list={list}/>
</div>

// JSX 事件
const eventList = <p onClick={this.clickHandler}>
some text
</p>

// JSX list
const listElem = <ul>{this.state.list.map((item, index) => {
return <li key={item.id}>index {index}; title {item.title}</li>
})}</ul>

编译后

// JSX 基本用法
const imgElem = /*#__PURE__*/React.createElement("div", {
id: "div1"
}, /*#__PURE__*/React.createElement("p", null, "some text"), /*#__PURE__*/React.createElement("img", {
src: imgUrl
})); // JSX style

const styleData = {
fontSize: '30px',
color: 'blue'
};
const styleElem = /*#__PURE__*/React.createElement("p", {
style: styleData
}, "\u8BBE\u7F6E style"); // JSX 加载组件

const app = /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Input, {
submitTitle: onSubmitTitle
}), /*#__PURE__*/React.createElement(List, {
list: list
})); // JSX 事件

const eventList = /*#__PURE__*/React.createElement("p", {
onClick: (void 0).clickHandler
}, "some text"); // JSX list

const listElem = /*#__PURE__*/React.createElement("ul", null, (void 0).state.list.map((item, index) => {
return /*#__PURE__*/React.createElement("li", {
key: item.id
}, "index ", index, "; title ", item.title);
}));

总结

  • React.createElement 即 h 函数,返回 vnode
  • 第一个参数,可能是组件,也可能是 html tag
  • 组件名,首字母必须大写(React 规定)
// 总结
React.createElement('div', null, [child1, child2, child3])
React.createElement('div', {...}, child1, child2, child3)
React.createElement(List, null, child1, child2, '文本节点')
// h 函数
// 返回 vnode
// patch