// 把虛擬對象轉(zhuǎn)成dom對象
function render(domObj) {
// 根據(jù)元素類型來創(chuàng)建dom
let el = document.createElement(domObj.type);
// 遍歷props對象,然后給創(chuàng)建的元素el設(shè)置屬性
for (let key in domObj.props) {
// 設(shè)置屬性的方法
setAttr(el, key, domObj.props[key]);
}
// 遍歷子節(jié)點(diǎn)數(shù)組
domObj.children.forEach(child = >{
// 需要注意的是:如果child是虛擬dom,就繼續(xù)遞歸渲染
if (child instanceof Element) {
child = render(child);
} else {
// 只是普通的文本內(nèi)容
child = document.createTextNode(child);
}
// 把子節(jié)點(diǎn)添加到父節(jié)點(diǎn)中
el.appendChild(child);
});
return el;
}
// 上面用到的設(shè)置屬性
function setAttr(node, key, value) {
// 需要判斷key是什么
switch (key) {
case 'value':
// 屬性是value就要看標(biāo)簽類型了,input和textarea的value就需要做區(qū)別
if (node.tagName.toLowerCase() === 'input' || node.tagName.toLowerCase() == 'textarea') {
node.value = value;
} else {
node.setAttribute(key, value);
}
break;
case 'style':
node.style.cssText = value;
break;
default:
node.setAttribute(key, value);
break;
}
}
// 將元素插入頁面
function renderDom(el, target) {
target.appendChild(el);
}
// 定義一個(gè)構(gòu)造函數(shù)來
class Element {
constructor(type, props, children) {
this.type = type;
this.props = props;
this.children = children;
}
}
//批量調(diào)用構(gòu)造函數(shù)
function createElement(type,props,children){
return new Element(type,props,children);
}
// 調(diào)用之前的createElement方法
let virtualDom = createElement('ul',{class:'list',style:'color:red;'},[
createElement('li',{class:'item'},['利群']),
createElement('li',{class:'item'},['玉溪']),
createElement('li',{class:'item'},['黃鶴樓']),
]);
// 對象形勢的結(jié)構(gòu)展示
console.log(virtualDom);
// 渲染dom
let el = render(virtualDom); // 得到dom元素
console.log(el);
renderDom(el,document.querySelector('body'));
虛擬dom轉(zhuǎn)化到真實(shí)dom
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。