Skip to content

Commit

Permalink
五: 5.Update — 更新 dom
Browse files Browse the repository at this point in the history
  • Loading branch information
zh-lx committed Nov 10, 2021
1 parent d5d5f6e commit bc90532
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
7 changes: 7 additions & 0 deletions src/mini-react/commit.js
@@ -1,3 +1,5 @@
import { updateAttributes } from './react-dom';

// 从根节点开始 commit
export function commitRoot(rootFiber) {
commitWork(rootFiber.child);
Expand All @@ -21,6 +23,11 @@ function commitWork(fiber) {
// targetPositionDom 不存在,插入到最后
parentDom.appendChild(fiber.stateNode);
}
} else if (fiber.flag === 'Update') {
const { children, ...newAttributes } = fiber.element.props;
const oldAttributes = Object.assign({}, fiber.alternate.element.props);
delete oldAttributes.children;
updateAttributes(fiber.stateNode, newAttributes, oldAttributes);
}

commitWork(fiber.sibling);
Expand Down
28 changes: 27 additions & 1 deletion src/mini-react/react-dom.js
Expand Up @@ -47,7 +47,33 @@ export function renderDom(element) {
}

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

Object.keys(attributes).forEach((key) => {
if (key.startsWith('on')) {
// 事件的处理
Expand Down

0 comments on commit bc90532

Please sign in to comment.