Skip to content

Commit

Permalink
二: 3.更新 dom 属性
Browse files Browse the repository at this point in the history
  • Loading branch information
zh-lx committed Nov 10, 2021
1 parent b5ef737 commit 79a61e7
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/mini-react/react-dom.js
Expand Up @@ -36,7 +36,7 @@ function renderDom(element) {

const {
type,
props: { children },
props: { children, ...attributes },
} = element;

if (typeof type === 'string') {
Expand Down Expand Up @@ -69,9 +69,37 @@ function renderDom(element) {
}
}

updateAttributes(dom, attributes);

return dom;
}

// 更新 dom 属性
function updateAttributes(dom, attributes) {
Object.keys(attributes).forEach((key) => {
if (key.startsWith('on')) {
// 事件的处理
const eventName = key.slice(2).toLowerCase();
dom.addEventListener(eventName, attributes[key]);
} else if (key === 'className') {
// className 的处理
const classes = attributes[key].split(' ');
classes.forEach((classKey) => {
dom.classList.add(classKey);
});
} else if (key === 'style') {
// style处理
const style = attributes[key];
Object.keys(style).forEach((styleName) => {
dom.style[styleName] = style[styleName];
});
} else {
// 其他属性的处理
dom[key] = attributes[key];
}
});
}

const ReactDOM = {
render,
};
Expand Down

0 comments on commit 79a61e7

Please sign in to comment.