平台无关性处理
约 281 字小于 1 分钟
2026-05-15
平台无关性处理
不管是 class 还是其他的 HTML 属性是依赖于 DOM 的,因此它们的处理也不应该在 runtime-core 中进行,而应该放在 runtime-dom 中进行处理
将上述逻辑进行抽离,放在 runtime-dom 中的 patchProps 函数中进行处理即可
patchProps.ts
function shouldSetAsProps(el, key, value) {
if (key === 'form' && el.tagName === 'INPUT') {
return false;
}
return key in el;
}
const options = {
createElement(tag) {
return document.createElement(tag);
},
setElementText(el, text) {
el.textContent = text;
},
insert(el, parent, anchor = null) {
parent.insertBefore(el, anchor);
},
patchProps(el, key, prevValue, nextValue) {
if (shouldSetAsProps(el, key, nextValue)) {
const type = typeof el[key];
if (type === "boolean" && nextValue === "") {
el[key] = true;
} else {
el[key] = nextValue;
}
} else {
el.setAttribute(key, nextValue);
}
}
}mountElement.ts
function createRenderer(options) {
const { createElement, insert, setElementText, patchProps } = options;
function mountElement(vnode, container) {
const el = createElement(vnode.type);
if (typeof vnode.children === "string") {
setElementText(el, vnode.children);
} else if (Array.isArray(vnode.children)) {
vnode.children.forEach((child) => {
patch(null, child, el);
});
}
if (vnode.props) {
for (const key in vnode.props) {
const value = vnode.props[key];
patchProps(el, key, null, value);
}
}
insert(el, container);
}
// ...
}重要
在经过统计后,实际 el.className 设置样式的效率是最高的,因此在 patchProps 中对于 class 的处理,最终还是要通过 el.className 来设置的,也就无需再 shouldSetAsProps 中单独去判断 class 了
