Skip to content

Commit 79a61e7

Browse files
committedNov 10, 2021
二: 3.更新 dom 属性
1 parent b5ef737 commit 79a61e7

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed
 

‎src/mini-react/react-dom.js

+29-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ function renderDom(element) {
3636

3737
const {
3838
type,
39-
props: { children },
39+
props: { children, ...attributes },
4040
} = element;
4141

4242
if (typeof type === 'string') {
@@ -69,9 +69,37 @@ function renderDom(element) {
6969
}
7070
}
7171

72+
updateAttributes(dom, attributes);
73+
7274
return dom;
7375
}
7476

77+
// 更新 dom 属性
78+
function updateAttributes(dom, attributes) {
79+
Object.keys(attributes).forEach((key) => {
80+
if (key.startsWith('on')) {
81+
// 事件的处理
82+
const eventName = key.slice(2).toLowerCase();
83+
dom.addEventListener(eventName, attributes[key]);
84+
} else if (key === 'className') {
85+
// className 的处理
86+
const classes = attributes[key].split(' ');
87+
classes.forEach((classKey) => {
88+
dom.classList.add(classKey);
89+
});
90+
} else if (key === 'style') {
91+
// style处理
92+
const style = attributes[key];
93+
Object.keys(style).forEach((styleName) => {
94+
dom.style[styleName] = style[styleName];
95+
});
96+
} else {
97+
// 其他属性的处理
98+
dom[key] = attributes[key];
99+
}
100+
});
101+
}
102+
75103
const ReactDOM = {
76104
render,
77105
};

0 commit comments

Comments
 (0)
Please sign in to comment.