Saber2pr's Blog

UpdateHostProperties

Update DOM

Dom operation

Function declaration

type Dict = { [k: string]: any };

function updateHostProperties(
  dom: (HTMLElement | Text) & Dict,
  oldProps: Dict,
  newProps: Dict
): void;

Three parameters, the type of dom is HTMLElement or Text, and & Dict is used to add attribute indexes to these two types. The second parameter is the old attribute of the dom node, that is, the alternate.props of host Fiber, and the third parameter is the props of the new host Fiber, which is provided by the VNode node generated by React.createElement.

Function realization

// props中需要过滤掉的属性
const fiberProps = ["children", "ref"];

function updateHostProperties(
  dom: (HTMLElement | Text) & Dict,
  oldProps: Dict,
  newProps: Dict
) {
  // 遍历newProps属性,diff
  Object.entries(newProps).forEach(([k, v]) => {
    // 过滤属性
    if (fiberProps.includes(k)) return;
    // style属性过滤掉,下文单独处理
    if (k === "style") return;
    // 新旧值没变化,跳过此次DOM操作
    if (oldProps[k] === v) return;
    // on开头的event事件handle变lower case
    if (k.startsWith("on")) k = k.toLowerCase();
    // 应用变化的属性到真实DOM
    dom[k] = v;
  });
  // style属性diff
  if ("style" in dom) {
    const newStyle = newProps.style || {};
    const oldStyle = oldProps.style || {};
    Object.entries(newStyle).forEach(([k, v]) => {
      // 新旧样式属性没变化,跳过此次DOM操作
      if (oldStyle[k] === v) return;
      // 应用变化的样式属性到真实DOM
      dom.style[k] = v;
    });
  }
}