Skip to content

Commit bc90532

Browse files
committed
五: 5.Update — 更新 dom
1 parent d5d5f6e commit bc90532

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/mini-react/commit.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { updateAttributes } from './react-dom';
2+
13
// 从根节点开始 commit
24
export function commitRoot(rootFiber) {
35
commitWork(rootFiber.child);
@@ -21,6 +23,11 @@ function commitWork(fiber) {
2123
// targetPositionDom 不存在,插入到最后
2224
parentDom.appendChild(fiber.stateNode);
2325
}
26+
} else if (fiber.flag === 'Update') {
27+
const { children, ...newAttributes } = fiber.element.props;
28+
const oldAttributes = Object.assign({}, fiber.alternate.element.props);
29+
delete oldAttributes.children;
30+
updateAttributes(fiber.stateNode, newAttributes, oldAttributes);
2431
}
2532

2633
commitWork(fiber.sibling);

src/mini-react/react-dom.js

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,33 @@ export function renderDom(element) {
4747
}
4848

4949
// 更新 dom 属性
50-
function updateAttributes(dom, attributes) {
50+
export function updateAttributes(dom, attributes, oldAttributes) {
51+
if (oldAttributes) {
52+
// 有旧属性,移除旧属性
53+
Object.keys(oldAttributes).forEach((key) => {
54+
if (key.startsWith('on')) {
55+
// 移除旧事件
56+
const eventName = key.slice(2).toLowerCase();
57+
dom.removeEventListener(eventName, oldAttributes[key]);
58+
} else if (key === 'className') {
59+
// className 的处理
60+
const classes = oldAttributes[key].split(' ');
61+
classes.forEach((classKey) => {
62+
dom.classList.remove(classKey);
63+
});
64+
} else if (key === 'style') {
65+
// style处理
66+
const style = oldAttributes[key];
67+
Object.keys(style).forEach((styleName) => {
68+
dom.style[styleName] = 'initial';
69+
});
70+
} else {
71+
// 其他属性的处理
72+
dom[key] = '';
73+
}
74+
});
75+
}
76+
5177
Object.keys(attributes).forEach((key) => {
5278
if (key.startsWith('on')) {
5379
// 事件的处理

0 commit comments

Comments
 (0)