把JSX语法转为虚拟DOM对象
一、JSX虚拟DOM渲染为真实DOM的原理和步骤
- 基于babel-preset-app把jsx语法变为React.createElement的模式
=>凡是遇到元素标签(或者组件)都要createElement
=>前两个参数是固定的:标签名(组件名)、属性对象(没有就是null),第三个及以后的参数是子元素 - 基于React.createElement方法的执行,创建出虚拟DOM对象(JSX对象)
=>首先是一个对象
=>type属性:存储的是标签名/组件名
=>peops属性:没有子元素,也没有任何行内属性,则为空对象{};如果createElement执行时传递了属性,那就把传递的属性都给props;如果有子元素,则props会新增一个children的属性,可能是一个值,也可能是一个数组 - 基于ReactDOM.render把创建的虚拟DOM对象渲染到页面指定的容器中
=>ReactDOM.render([JSXOBJ], [CONTAINER], [CALLBACK])
=>[CALLBACK]渲染完成之后触发的回调函数,在这里可以获取到真实的DOM
二、代码实现
let jsxOBJ = React.createElement("div", null, React.createElement("h2", {
style: {
color: 'red'
}
}, "\u6211\u662F\u6807\u9898"), "\u54C8\u54C8", React.createElement("p", {
className: "box",
id: "hhh"
}, "\u6B22\u8FCE\u6765\u5230react\u8BFE\u7A0B\u5B66\u4E60"), React.createElement("span", {
id: "12"
}), React.createElement("i", null));
console.log(jsxOBJ);
React.createElement = function(type, props, ...children){
let jsxOBJ = {
type,
props: {}
};
if(props) {
jsxOBJ.props = {...props}
}
if(children.length) {
if(children.length === 1) {
jsxOBJ.props.children = children[0];
}else {
jsxOBJ.props.children = children;
}
}
return jsxOBJ;
}