React 深度學習:4. 建立 DOM 元素

React 初次渲染的時候無非會經歷以下四個步驟:javascript


ReactElement 元素的建立,以及它如何表達嵌套在上個章節中也已闡述。React 的難點就在於如何進行數據處理,而且保持高效,咱們暫且忽略它。秉持由淺入深的原則進行學習。css

想要從 ReactElement 元素的層層嵌套結構中解析出 DOM,能直接想到的辦法就是使用遞歸。在遇到每一層的時候根據元素類型建立不一樣的 DOM 元素,最後將這一個龐大的 DOM 元素樹插入到真實的 DOM 中。html

這些功能,都集中在:java

packages/react-dom/src/client/ReactDOMComponent.js

createElement

/** * 建立元素 * @param type * @param props * @param rootContainerElement * @param parentNamespace * @returns {Element} */
export function createElement( type: string, props: Object, rootContainerElement: Element | Document, parentNamespace: string, ): Element {
  let isCustomComponentTag;

  // 咱們在它們的父容器的命名空間中建立標記,除了 HTML 標籤沒有命名空間。
  // getOwnerDocumentFromRootContainer 方法用來獲取 document
  const ownerDocument: Document = getOwnerDocumentFromRootContainer(
    rootContainerElement,
  );
  let domElement: Element;
  let namespaceURI = parentNamespace;
  if (namespaceURI === HTML_NAMESPACE) {
    namespaceURI = getIntrinsicNamespace(type);
  }
  if (namespaceURI === HTML_NAMESPACE) {

    if (type === 'script') {
      // 經過 .innerHTML 建立腳本,這樣它的 「parser-inserted」 標誌就被設置爲true,並且不會執行
      const div = ownerDocument.createElement('div');
      div.innerHTML = '<script><' + '/script>'; // eslint-disable-line
      // 這將保證生成一個腳本元素。
      const firstChild = ((div.firstChild: any): HTMLScriptElement);
      domElement = div.removeChild(firstChild);
    } else if (typeof props.is === 'string') {
      // $FlowIssue `createElement` 應該爲 Web Components 更新
      domElement = ownerDocument.createElement(type, {is: props.is});
    } else {
      // 由於 Firefox bug,分離 else 分支,而不是使用 `props.is || undefined`
      // 參見 https://github.com/facebook/react/pull/6896
      // 和 https://bugzilla.mozilla.org/show_bug.cgi?id=1276240
      domElement = ownerDocument.createElement(type);
      // 一般在 `setInitialDOMProperties` 中分配屬性,
      // 可是 `select` 上的 `multiple` 和 `size` 屬性須要在 `option` 被插入以前添加。
      // 這能夠防止:
      // 一個錯誤,其中 `select` 不能滾動到正確的選項,由於單一的 `select` 元素自動選擇第一項 #13222
      // 一個 bug,其中 `select` 將第一個項目設置爲 selected,而忽略 `size` 屬性 #14239
      // 參見 https://github.com/facebook/react/issues/13222
      // 和 https://github.com/facebook/react/issues/14239
      if (type === 'select') {
        const node = ((domElement: any): HTMLSelectElement);
        if (props.multiple) {
          node.multiple = true;
        } else if (props.size) {
          // 設置大於 1 的 size 會使 select 的行爲相似於 `multiple=true`,其中可能沒有選擇任何選項。
          // select 只有在「單一選擇模式」下才須要這樣作。
          node.size = props.size;
        }
      }
    }
  } else {
    domElement = ownerDocument.createElementNS(namespaceURI, type);
  }

  return domElement;
}複製代碼

createElement 方法會根據不一樣的類型建立不一樣的 DOM 元素。值得指出的是,它不只支持原生的 html 標籤,還支持 WebComponent。
node

createTextNode

export function createTextNode(
  text: string,
  rootContainerElement: Element | Document,
): Text {
  return getOwnerDocumentFromRootContainer(rootContainerElement).createTextNode(
    text,
  );
}複製代碼

createTextNode 方法建立了一個文本節點
react

setInitialProperties

export function setInitialProperties( domElement: Element, tag: string, rawProps: Object, rootContainerElement: Element | Document, ): void {
  const isCustomComponentTag = isCustomComponent(tag, rawProps);

  // TODO: Make sure that we check isMounted before firing any of these events.
  let props: Object;
  switch (tag) {
    case 'iframe':
    case 'object':
      trapBubbledEvent(TOP_LOAD, domElement);
      props = rawProps;
      break;
    case 'video':
    case 'audio':
      // Create listener for each media event
      for (let i = 0; i < mediaEventTypes.length; i++) {
        trapBubbledEvent(mediaEventTypes[i], domElement);
      }
      props = rawProps;
      break;
    case 'source':
      trapBubbledEvent(TOP_ERROR, domElement);
      props = rawProps;
      break;
    case 'img':
    case 'image':
    case 'link':
      trapBubbledEvent(TOP_ERROR, domElement);
      trapBubbledEvent(TOP_LOAD, domElement);
      props = rawProps;
      break;
    case 'form':
      trapBubbledEvent(TOP_RESET, domElement);
      trapBubbledEvent(TOP_SUBMIT, domElement);
      props = rawProps;
      break;
    case 'details':
      trapBubbledEvent(TOP_TOGGLE, domElement);
      props = rawProps;
      break;
    case 'input':
      ReactDOMInputInitWrapperState(domElement, rawProps);
      props = ReactDOMInputGetHostProps(domElement, rawProps);
      trapBubbledEvent(TOP_INVALID, domElement);
      // For controlled components we always need to ensure we're listening
      // to onChange. Even if there is no listener.
      ensureListeningTo(rootContainerElement, 'onChange');
      break;
    case 'option':
      ReactDOMOptionValidateProps(domElement, rawProps);
      props = ReactDOMOptionGetHostProps(domElement, rawProps);
      break;
    case 'select':
      ReactDOMSelectInitWrapperState(domElement, rawProps);
      props = ReactDOMSelectGetHostProps(domElement, rawProps);
      trapBubbledEvent(TOP_INVALID, domElement);
      // For controlled components we always need to ensure we're listening
      // to onChange. Even if there is no listener.
      ensureListeningTo(rootContainerElement, 'onChange');
      break;
    case 'textarea':
      ReactDOMTextareaInitWrapperState(domElement, rawProps);
      props = ReactDOMTextareaGetHostProps(domElement, rawProps);
      trapBubbledEvent(TOP_INVALID, domElement);
      // For controlled components we always need to ensure we're listening
      // to onChange. Even if there is no listener.
      ensureListeningTo(rootContainerElement, 'onChange');
      break;
    default:
      props = rawProps;
  }

  assertValidProps(tag, props);

  setInitialDOMProperties(
    tag,
    domElement,
    rootContainerElement,
    props,
    isCustomComponentTag,
  );

  switch (tag) {
    case 'input':
      // TODO: Make sure we check if this is still unmounted or do any clean
      // up necessary since we never stop tracking anymore.
      track((domElement: any));
      ReactDOMInputPostMountWrapper(domElement, rawProps, false);
      break;
    case 'textarea':
      // TODO: Make sure we check if this is still unmounted or do any clean
      // up necessary since we never stop tracking anymore.
      track((domElement: any));
      ReactDOMTextareaPostMountWrapper(domElement, rawProps);
      break;
    case 'option':
      ReactDOMOptionPostMountWrapper(domElement, rawProps);
      break;
    case 'select':
      ReactDOMSelectPostMountWrapper(domElement, rawProps);
      break;
    default:
      if (typeof props.onClick === 'function') {
        // TODO: This cast may not be sound for SVG, MathML or custom elements.
        trapClickOnNonInteractiveElement(((domElement: any): HTMLElement));
      }
      break;
  }
}複製代碼

trapBubbledEvent 爲元素添加事件。
git

setInitialDOMProperties

/** * 設置初始 DOM 屬性 * @param tag * @param domElement * @param rootContainerElement * @param nextProps * @param isCustomComponentTag */
function setInitialDOMProperties( tag: string, domElement: Element, rootContainerElement: Element | Document, nextProps: Object, isCustomComponentTag: boolean, ): void {
  for (const propKey in nextProps) {
    if (!nextProps.hasOwnProperty(propKey)) {
      continue;
    }
    // 當前遍歷的屬性值
    const nextProp = nextProps[propKey];
    // 設置默認 style 標籤的屬性
    if (propKey === STYLE) {
      if (__DEV__) {
        if (nextProp) {
          // Freeze the next style object so that we can assume it won't be
          // mutated. We have already warned for this in the past.
          Object.freeze(nextProp);
        }
      }
      // 使用 node.style['cssFloat'] 這樣的對象語法來爲節點設置樣式
      // 依賴於 `updateStylesByID` 而不是 `styleUpdates`.
      setValueForStyles(domElement, nextProp);
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { // 單獨處理 html 字符串
      const nextHtml = nextProp ? nextProp[HTML] : undefined;
      if (nextHtml != null) {
        setInnerHTML(domElement, nextHtml); // 設置 innerHTML
      }
    } else if (propKey === CHILDREN) { // 處理 children 屬性
      if (typeof nextProp === 'string') {
        // 避免在文本爲空時設置初始文本內容。
        // 在IE11中,在 <textarea> 上設置 textContent
        // 將致使佔位符(placeholder)不顯示在 <textarea> 中,直到它再次被 focus 和 blur。
        // https://github.com/facebook/react/issues/6731#issuecomment-254874553
        const canSetTextContent = tag !== 'textarea' || nextProp !== '';
        if (canSetTextContent) {
          setTextContent(domElement, nextProp); // 設置文本
        }
      } else if (typeof nextProp === 'number') {
        setTextContent(domElement, '' + nextProp); // 設置文本
      }
    } else if (
      propKey === SUPPRESS_CONTENT_EDITABLE_WARNING ||
      propKey === SUPPRESS_HYDRATION_WARNING
    ) {
      // Noop
    } else if (propKey === AUTOFOCUS) {
      // We polyfill it separately on the client during commit.
      // We could have excluded it in the property list instead of
      // adding a special case here, but then it wouldn't be emitted
      // on server rendering (but we *do* want to emit it in SSR).
    } else if (registrationNameModules.hasOwnProperty(propKey)) {
      if (nextProp != null) {
        if (__DEV__ && typeof nextProp !== 'function') {
          warnForInvalidEventListener(propKey, nextProp);
        }
        ensureListeningTo(rootContainerElement, propKey); // 事件監聽
      }
    } else if (nextProp != null) {
      // 設置屬性值
      setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag);
    }
  }
}複製代碼

setInitialDOMProperties 用於設置 DOM 元素初始的屬性。
github

  • 首先,它會遍歷全部的屬性,過濾掉非自身的屬性
  • 處理 dangerouslySetInnerHTML 屬性,該屬性接收一個 { __html: '' } 格式的對象,所以這裏取出其 __html,使用   setInnerHTML  方法將其設置爲 innerHTML
  • 處理字符串和數字文本,使用文本節點的 .nodeValue 屬性設置其文本內容
  • 處理事件處理函數屬性
  • 使用  setValueForProperty  方法設置普通屬性的值

其中有意思的是 React 處理 html 字符串的方式,將其放置在了 svg 標籤中。爲什麼如此處理?瀏覽器

const setInnerHTML = createMicrosoftUnsafeLocalFunction(function( node: Element, html: string, ): void {

  // IE 沒有針對 SVG 節點的 innerHTML,
  // 所以咱們將新標記注入臨時節點,而後將子節點移動到目標節點
  // 也就是說不能經過 SVG 的 innerHTML 屬性直接賦值

  if (node.namespaceURI === Namespaces.svg && !('innerHTML' in node)) {
    reusableSVGContainer =
      reusableSVGContainer || document.createElement('div');
    reusableSVGContainer.innerHTML = '<svg>' + html + '</svg>';
    const svgNode = reusableSVGContainer.firstChild;
    while (node.firstChild) {
      node.removeChild(node.firstChild);
    }
    while (svgNode.firstChild) {
      node.appendChild(svgNode.firstChild);
    }
  } else {
    node.innerHTML = html;
  }
});複製代碼

updateProperties

/** * 應用 diff,更新屬性 * @param domElement * @param updatePayload * @param tag * @param lastRawProps * @param nextRawProps */
export function updateProperties( domElement: Element, updatePayload: Array<any>, tag: string, lastRawProps: Object, nextRawProps: Object, ): void {
  // 更新名稱前的選中狀態
  // 在更新過程當中,可能會有多個被選中項
  // 當一個選中的單選框改變名稱時,瀏覽器會使其餘的單選框的選中狀態爲 false
  if (
    tag === 'input' &&
    nextRawProps.type === 'radio' &&
    nextRawProps.name != null
  ) {
    ReactDOMInputUpdateChecked(domElement, nextRawProps); // 更新 radio 的 Checked 狀態
  }

  const wasCustomComponentTag = isCustomComponent(tag, lastRawProps);
  const isCustomComponentTag = isCustomComponent(tag, nextRawProps);
  // 應用 diff.
  updateDOMProperties(
    domElement,
    updatePayload,
    wasCustomComponentTag,
    isCustomComponentTag,
  );

  // TODO: Ensure that an update gets scheduled if any of the special props
  // changed.
  switch (tag) {
    case 'input':
      // 在更新 props 以後更新 input 的包裝器。
      // 這必須發生在 `updateDOMProperties` 以後。
      // 不然,HTML5 輸入驗證將發出警告並阻止新值的分配。
      ReactDOMInputUpdateWrapper(domElement, nextRawProps);
      break;
    case 'textarea':
      ReactDOMTextareaUpdateWrapper(domElement, nextRawProps);
      break;
    case 'select':
      // <select> 的值更新須要在 <option> 子元素 reconciliation 以後發生
      ReactDOMSelectPostUpdateWrapper(domElement, nextRawProps);
      break;
  }
}複製代碼


updateDOMProperties

function updateDOMProperties( domElement: Element, updatePayload: Array<any>, wasCustomComponentTag: boolean, isCustomComponentTag: boolean, ): void {
  // TODO: Handle wasCustomComponentTag
  for (let i = 0; i < updatePayload.length; i += 2) {
    const propKey = updatePayload[i];
    const propValue = updatePayload[i + 1];
    if (propKey === STYLE) {
      setValueForStyles(domElement, propValue);
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
      setInnerHTML(domElement, propValue);
    } else if (propKey === CHILDREN) {
      setTextContent(domElement, propValue);
    } else {
      setValueForProperty(domElement, propKey, propValue, isCustomComponentTag);
    }
  }
}複製代碼

因爲當前元素已經存在於 dom 中了,所以只須要根據傳入的數據進行更新就好了。bash

diffProperties

/** * 計算兩個對象之間的差別。 * 爲何須要更新,無非三種狀況: * 1. 以前有,以後沒有,須要刪除 * 2. 以前沒有,以後有,須要新增 * 3. 先後值不同,須要更新 * * 但在 react 的實現中,新增和更新的邏輯都是同樣,所以能夠合併: * 1. 以前有,以後沒有,須要刪除 * 2. 先後值不同,須要更新 * * @param domElement * @param tag * @param lastRawProps * @param nextRawProps * @param rootContainerElement * @returns {Array<*>} */
export function diffProperties( domElement: Element, tag: string, lastRawProps: Object, nextRawProps: Object, rootContainerElement: Element | Document, ): null | Array<mixed> {
  if (__DEV__) {
    validatePropertiesInDevelopment(tag, nextRawProps);
  }

  let updatePayload: null | Array<any> = null;

  let lastProps: Object;
  let nextProps: Object;
  switch (tag) {
    case 'input':
      lastProps = ReactDOMInputGetHostProps(domElement, lastRawProps);
      nextProps = ReactDOMInputGetHostProps(domElement, nextRawProps);
      updatePayload = [];
      break;
    case 'option':
      lastProps = ReactDOMOptionGetHostProps(domElement, lastRawProps);
      nextProps = ReactDOMOptionGetHostProps(domElement, nextRawProps);
      updatePayload = [];
      break;
    case 'select':
      lastProps = ReactDOMSelectGetHostProps(domElement, lastRawProps);
      nextProps = ReactDOMSelectGetHostProps(domElement, nextRawProps);
      updatePayload = [];
      break;
    case 'textarea':
      lastProps = ReactDOMTextareaGetHostProps(domElement, lastRawProps);
      nextProps = ReactDOMTextareaGetHostProps(domElement, nextRawProps);
      updatePayload = [];
      break;
    default:
      lastProps = lastRawProps;
      nextProps = nextRawProps;
      if (
        typeof lastProps.onClick !== 'function' &&
        typeof nextProps.onClick === 'function'
      ) {
        // TODO: This cast may not be sound for SVG, MathML or custom elements.
        trapClickOnNonInteractiveElement(((domElement: any): HTMLElement));
      }
      break;
  }

  assertValidProps(tag, nextProps);

  let propKey;
  let styleName;
  let styleUpdates = null; // 用以記錄須要更新的樣式,1. 須要清除的樣式 2. 新增的或者值改變的樣式
  for (propKey in lastProps) {
    // nextProps 有此屬性不處理
    // lastProps 沒有此屬性不處理
    // lastProps 此屬性值爲 null 或 undefined 不處理
    // 也就是說,只處理 lastProps 有,但 nextProps 沒有的,且 lastProps 中值不爲 null 或 undefined 的
    // 更直白點說就是重置須要刪除的屬性
    if (
      nextProps.hasOwnProperty(propKey) ||
      !lastProps.hasOwnProperty(propKey) ||
      lastProps[propKey] == null
    ) {
      continue;
    }
    if (propKey === STYLE) { // 處理 style 屬性
      const lastStyle = lastProps[propKey];
      for (styleName in lastStyle) {
        if (lastStyle.hasOwnProperty(styleName)) {
          if (!styleUpdates) {
            styleUpdates = {};
          }
          styleUpdates[styleName] = ''; // 清除以前的樣式
        }
      }
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) {
      // Noop. This is handled by the clear text mechanism.
    } else if (
      propKey === SUPPRESS_CONTENT_EDITABLE_WARNING ||
      propKey === SUPPRESS_HYDRATION_WARNING
    ) {
      // Noop
    } else if (propKey === AUTOFOCUS) {
      // 無操做。不管如何,它都不能在更新上工做。
    } else if (registrationNameModules.hasOwnProperty(propKey)) {
      // 這是一個特例。若是任何偵聽器更新,
      // 咱們須要確保 "current" props 指針獲得更新,
      // 所以咱們須要一個提交來更新此元素。
      if (!updatePayload) {
        updatePayload = [];
      }
    } else {
      // 對於全部其餘已刪除的屬性,咱們將其添加到隊列中。相反,咱們在提交階段使用白名單。
      (updatePayload = updatePayload || []).push(propKey, null);
    }
  }
  for (propKey in nextProps) {
    const nextProp = nextProps[propKey];
    const lastProp = lastProps != null ? lastProps[propKey] : undefined;
    // nextProps 沒有的屬性不添加到更新
    // nextProp 和 lastProp 相等不處理
    // nextProp 和 lastProp 都爲 null 或 undefined 不處理
    // 也就是說值處理 nextProps 有的,值不爲 null 或 undefined,且 nextProp 和 lastProp 的狀況
    // 更直白點說就是更新值發生改變的屬性
    if (
      !nextProps.hasOwnProperty(propKey) ||
      nextProp === lastProp ||
      (nextProp == null && lastProp == null)
    ) {
      continue;
    }
    if (propKey === STYLE) {
      if (__DEV__) {
        if (nextProp) {
          // Freeze the next style object so that we can assume it won't be
          // mutated. We have already warned for this in the past.
          Object.freeze(nextProp);
        }
      }
      if (lastProp) {
        // Unset styles on `lastProp` but not on `nextProp`.
        for (styleName in lastProp) {
          if ( // lastProp 有這個屬性,而且 nextProp 不存在或者沒有此屬性。
            lastProp.hasOwnProperty(styleName) &&
            (!nextProp || !nextProp.hasOwnProperty(styleName))
          ) {
            if (!styleUpdates) {
              styleUpdates = {};
            }
            styleUpdates[styleName] = ''; // 置空樣式屬性值
          }
        }
        // 更新自 `lastProp` 以來更改的樣式。
        for (styleName in nextProp) {
          // nextProp 存在的樣式屬性,且先後值不同
          if (
            nextProp.hasOwnProperty(styleName) &&
            lastProp[styleName] !== nextProp[styleName]
          ) {
            if (!styleUpdates) {
              styleUpdates = {};
            }
            styleUpdates[styleName] = nextProp[styleName];
          }
        }
      } else { // 之前不存在 style 屬性
        // 依賴於 `updateStylesByID` 而不是 `styleUpdates`.
        if (!styleUpdates) {
          if (!updatePayload) {
            updatePayload = [];
          }
          updatePayload.push(propKey, styleUpdates); // 等同於 updatePayload.push(propKey, null);
        }
        styleUpdates = nextProp;
      }
    } else if (propKey === DANGEROUSLY_SET_INNER_HTML) {
      const nextHtml = nextProp ? nextProp[HTML] : undefined; // 取出 .__html 中存儲的 html 字符串
      const lastHtml = lastProp ? lastProp[HTML] : undefined; // 取出 .__html 中存儲的 html 字符串
      if (nextHtml != null) {
        if (lastHtml !== nextHtml) {
          (updatePayload = updatePayload || []).push(propKey, '' + nextHtml); // 須要更新的 html
        }
      } else {
        // TODO: It might be too late to clear this if we have children
        // inserted already.
      }
    } else if (propKey === CHILDREN) {
      // 處理純文本
      if (
        lastProp !== nextProp &&
        (typeof nextProp === 'string' || typeof nextProp === 'number')
      ) {
        (updatePayload = updatePayload || []).push(propKey, '' + nextProp);
      }
    } else if (
      propKey === SUPPRESS_CONTENT_EDITABLE_WARNING ||
      propKey === SUPPRESS_HYDRATION_WARNING
    ) {
      // Noop
    } else if (registrationNameModules.hasOwnProperty(propKey)) {
      if (nextProp != null) {
        // We eagerly listen to this even though we haven't committed yet.
        if (__DEV__ && typeof nextProp !== 'function') {
          warnForInvalidEventListener(propKey, nextProp);
        }
        ensureListeningTo(rootContainerElement, propKey);
      }
      if (!updatePayload && lastProp !== nextProp) {
        // 這是一個特例。若是任何偵聽器更新,
        // 咱們須要確保 "current" props 指針獲得更新,
        // 所以咱們須要一個提交來更新此元素。
        updatePayload = [];
      }
    } else {
      // 對於任何其餘屬性,咱們老是將其添加到隊列中,而後在提交期間使用白名單過濾掉。
      (updatePayload = updatePayload || []).push(propKey, nextProp);
    }
  }
  if (styleUpdates) {
    if (__DEV__) {
      validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]);
    }
    (updatePayload = updatePayload || []).push(STYLE, styleUpdates); // 添加樣式更新
  }
  return updatePayload;
}複製代碼

diffHydratedProperties

diffHydratedText

計算文本節點之間的差別

/** * 計算文本節點之間的差別。 * @param textNode * @param text * @returns {boolean} */
function diffHydratedText(textNode: Text, text: string): boolean {
  const isDifferent = textNode.nodeValue !== text;
  return isDifferent;
}複製代碼

restoreControlledState

/** * 恢復受控狀態 * @param domElement * @param tag * @param props */
export function restoreControlledState( domElement: Element, tag: string, props: Object, ): void {
  switch (tag) {
    case 'input':
      ReactDOMInputRestoreControlledState(domElement, props);
      return;
    case 'textarea':
      ReactDOMTextareaRestoreControlledState(domElement, props);
      return;
    case 'select':
      ReactDOMSelectRestoreControlledState(domElement, props);
      return;
  }
}複製代碼

遺留問題

上面建立的元素只是建立了一個,如何建立一個 DOM 樹?

相關文章
相關標籤/搜索