# JSX解析原理
JSX语法糖的原理是什么,先来了解React的一个函数。
# creatElement
React.createElement(
type,
[props],
[...children]
)
1
2
3
4
5
2
3
4
5
第一个参数必填,是html标签名
第二个参数就是React中组件的Props
第三个组件是子组件
- 下面看一个jsx转js的例子
jsx
render() {
const list = this.props.data
return (
<ul>
{list.map((item,index)=>{
return <li key={index}>{item}</li>
})
}
)
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
js
function render(){
const list = this.props.data
return React.createElement(
"ul",
null,
list.map((item)=>{
return React.createElement(
"li",
{key: index},
item
)
})
)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
这么一看我们就明白了,为什么jsx中只允许使用简单的表达式,同时节点拥有this.props.children。
有兴趣的可以通过安装babel-plugin-transform-react-jsx查看编译后的js代码
babel --plugins transform-react-jsx demo.jsx
1