React源码解析-React.Children

1,767 阅读4分钟

前言:

本文章是基于16.13.1的react版本。相较于之前版本,去除了**pool的概念,并且代码上在函数的调用方面也做了精简和优化,使我们理解源码上更方便。**

React.Children是顶层API之一,提供了对this.props.children处理的工具,this.props.children可以为任何数据类型。React.Children有5个方法:React.Children.map(),React.Children.forEach()、React.Children.count()、React.Children.only()、React.Children.toArray()。他们都在ReactChildren.js这个文件里:

/packages/react/src/ReactChildren.js

export {
  forEachChildren as forEach,
  mapChildren as map,
  countChildren as count,
  onlyChild as only,
  toArray,
};

本篇文章主要是分析map方法,搞懂了map里面的处理逻辑,其他的几个都能触类旁通。

首先,我们就拿以下这段代码块为例,带入map的源码讲解方便理解。

此时props.children就是一个包含两个子元素的数组,打印出来结果如下图所示:

一、React.Children.map()

1. 流程图

2.源码解析

我们执行以下操作,来思考下最后的输出结果是什么呢?

React.Children.map(props.children, c => [c, [c, c]])

进入源码进行分析:

function mapChildren(
  children: ?ReactNodeList, // props.children传进来的数组
  func: MapFunc, // c => [c, [c, c]]
  context: mixed,
): ?Array<React$Node> {
  if (children == null) {
    return children;
  }
  const result = [];
  let count = 0;
  mapIntoArray(children, result, '', '', function(child) {
    return func.call(context, child, count++);
  });
  return result;
}
// 第一次children是初始值:{
  children: [{...}, {...}],
  array: [],
  '',
  '',
  c => [c, [c, c]],
};
// 第二次,遍历children里的第一项:{
  child: {...}, 
  array: [], 
  escapedPrefix: '', 
  nextName: '.0', 
  callback: c => [c, [c, c]],
}
// 第三次,children的第一个子节点的执行结果入参:{
  mappedChild: [c, [c, c]],
  array: [],
  escapedChildKey: '.0/',
  '',
  c => c
}
// 第四次,children的第一个子节点的执行结果的第一个item:{
  child: c, // 还是第一个子节点
  array: [], 
  escapedPrefix: '.0/', 
  nextName: '.0', 
  callback: c => c,
}
// 第五次,children的第一个子节点的执行结果的第二个item:{
  child: [c,c], 
  array: [c], 
  escapedPrefix: '.0/', 
  nextName: '.1', 
  callback: c => c,
}
// 第六次,children的第一个子节点的执行结果的第二个item[c,c]的第一项:{
  child: c,
  array: [c], 
  escapedPrefix: '.1/', 
  nextName: '.1:0', 
  callback: c => c,
}
// 第七次,children的第一个子节点的执行结果的第二个item[c,c]的第二项,参数{
  child: c,
  array: [c,c], 
  escapedPrefix: '.1/', 
  nextName: '.1:1', 
  callback: c => c,
}
// 第八次,children的第二个子节点:同理
// ...

function mapIntoArray(
  children: ?ReactNodeList,
  array: Array<React$Node>,
  escapedPrefix: string,
  nameSoFar: string,
  callback: (?React$Node) => ?ReactNodeList,
): number {
  const type = typeof children;

  if (type === 'undefined' || type === 'boolean') {
    // All of the above are perceived as null.
    children = null;
  }

  let invokeCallback = false;

  if (children === null) {
    invokeCallback = true;
  } else {
    switch (type) {
      case 'string':
      case 'number':
        invokeCallback = true;
        break;
      case 'object':
        switch ((children: any).$typeof) {
          case REACT_ELEMENT_TYPE:
          case REACT_PORTAL_TYPE:
            invokeCallback = true;
        }
    }
  }

  // children的第一个子节点符合条件,进入判断 
  // children的第一个子节点的执行结果的第一个item,进入判断 
  // children的第一个子节点的执行结果的第二个item[c,c]的第一项,进入判断
  // children的第一个子节点的执行结果的第二个item[c,c]的第二项,进入判断
  if (invokeCallback) {
    const child = children;

    // 执行callback,callback为 c => [c, [c, c]], mappedChild为[c, [c, c]];
    // 执行callback,callback为 c => c, mappedChild为c;
    // 执行callback,callback为 c => c, mappedChild为c;
    // 执行callback,callback为 c => c, mappedChild为c;
    let mappedChild = callback(child);

    // children的第一个子节点,childKey='.0';
    // children的第一个子节点的执行结果的第一个item,childKey='.0';
    // children的第一个子节点的执行结果的第二个item[c,c]的第一项,childKey='.1:0';
    // children的第一个子节点的执行结果的第二个item[c,c]的第二项,childKey='.1:1';
    const childKey =
      nameSoFar === '' ? SEPARATOR + getElementKey(child, 0) : nameSoFar;

    // children的第一个子节点mappedChild满足数组条件
    // children的第一个子节点的执行结果的第一个item不满足数组条件
    // children的第一个子节点的执行结果的第二个item[c,c]的第一项不满足数组条件
    // children的第一个子节点的执行结果的第二个item[c,c]的第二项不满足数组条件
    if (Array.isArray(mappedChild)) {
      let escapedChildKey = '';
      if (childKey != null) {
        // escapedChildKey为'.0/'
        escapedChildKey = escapeUserProvidedKey(childKey) + '/';
      }
      // children的第一个子节点的执行结果入参:{
        mappedChild: [c, [c, c]],
        array: [],
        escapedChildKey: '.0/',
        '',
        c => c
      }
      mapIntoArray(mappedChild, array, escapedChildKey, '', c => c);
    } else if (mappedChild != null) {
      if (isValidElement(mappedChild)) {
        // clone节点的信息,替换了key值
        mappedChild = cloneAndReplaceKey(
          mappedChild,
          // Keep both the (mapped) and old keys if they differ, just as
          // traverseAllChildren used to do for objects as children
          escapedPrefix +
            // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key
            (mappedChild.key && (!child || child.key !== mappedChild.key)
              ? // $FlowFixMe Flow incorrectly thinks existing element's key can be a number
                escapeUserProvidedKey('' + mappedChild.key) + '/'
              : '') +
            childKey,
        );
      }
      // children的第一个子节点的执行结果的第一个item, '.0/.0'
      // children的第一个子节点的执行结果的第二个item[c,c]的第一项,'.0/.1:0'
      // children的第一个子节点的执行结果的第二个item[c,c]的第二项, '.0/.1:1'
      // 同理可得:'.1/.0'
      // 同理可得:'.1/.1:0'
      // 同理可得:'.1/.1:1'
      array.push(mappedChild);
    }
    return 1;
  }

  let child;
  let nextName;
  let subtreeCount = 0; // Count of children found in the current subtree.
  const nextNamePrefix =
    nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;

  // 第一次:直接走到这里,此时children是初始的那个数组;
  // 第二次:children的第一个子节点的执行结果走到这里;
  // 第三次:children的第一个子节点的执行结果的第二项走到这里;
  if (Array.isArray(children)) {
    for (let i = 0; i < children.length; i++) {
      child = children[i];
      nextName = nextNamePrefix + getElementKey(child, i);

      // 第一次children的第一个子节点:参数{
        child: {...}, // 第一个子节点
        array: [], 
        escapedPrefix: '', 
        nextName: '.0', 
        callback: c => [c, [c, c]],
      }
      // 第二次children的第一个子节点的执行结果的第一个item,遍历0,参数{
        child: c,
        array: [], 
        escapedPrefix: '.0/', 
        nextName: '.0', 
        callback: c => c,
      }
      // 第三次children的第一个子节点的执行结果的第二个item,遍历1,参数{
        child: [c,c],
        array: [c], 
        escapedPrefix: '.0/', 
        nextName: '.1', 
        callback: c => c,
      }
      // 第四次children的第一个子节点的执行结果的第二个item[c,c]的第一项,遍历0,参数{
        child: c,
        array: [c], 
        escapedPrefix: '.1/', 
        nextName: '.1:0', 
        callback: c => c,
      }
      // 第五次children的第一个子节点的执行结果的第二个item[c,c]的第二项,遍历1,参数{
        child: c,
        array: [c,c], 
        escapedPrefix: '.1/', 
        nextName: '.1:1', 
        callback: c => c,
      }
      // 第六次children的第二个子节点:同理{
        child: {...}, // 第二个子节点
        array: [c,c,c], 
        escapedPrefix: '', 
        nextName: '.1', 
        callback: c => [c, [c, c]],
      }
      subtreeCount += mapIntoArray(
        child,
        array,
        escapedPrefix,
        nextName,
        callback,
      );
    }
  } else {
    const iteratorFn = getIteratorFn(children);
    if (typeof iteratorFn === 'function') {
      const iterableChildren: Iterable<React$Node> & {
        entries: any,
      } = (children: any);

      if (__DEV__) {
        // Warn about using Maps as children
        if (iteratorFn === iterableChildren.entries) {
          if (!didWarnAboutMaps) {
            console.warn(
              'Using Maps as children is not supported. ' +
                'Use an array of keyed ReactElements instead.',
            );
          }
          didWarnAboutMaps = true;
        }
      }

      const iterator = iteratorFn.call(iterableChildren);
      let step;
      let ii = 0;
      while (!(step = iterator.next()).done) {
        child = step.value;
        nextName = nextNamePrefix + getElementKey(child, ii++);
        subtreeCount += mapIntoArray(
          child,
          array,
          escapedPrefix,
          nextName,
          callback,
        );
      }
    } else if (type === 'object') {
      const childrenString = '' + (children: any);
      invariant(
        false,
        'Objects are not valid as a React child (found: %s). ' +
          'If you meant to render a collection of children, use an array ' +
          'instead.',
        childrenString === '[object Object]'
          ? 'object with keys {' + Object.keys((children: any)).join(', ') + '}'
          : childrenString,
      );
    }
  }

  return subtreeCount;
}

执行结果:

3.总结:

map就是将嵌套的数组进行平铺,并将结果return出来。大家可以发现,最后return出来的相同的节点(比如下标为0、1、2的,他们都是第一个子节点),他们其他的属性都一样除了key值。key的生成规则我在代码里做了详细的注释,可以到上面的代码里去看(我以节点没有设置key的情况写的)。

那么我们在思考下,再往里嵌套一层key的值是什么呢?

React.Children.map(props.children, c => [c, [c, [c,c]]])

他的执行结果是这样的:

大家发现规律了吗?当节点本身没有设置key时,/前面代表了节点的位置下标,/后面表示当前元素在数组中的位置下标,深度用:表示。

如果我们自己设置了key呢?他的展示就是如下所示,大家可以自己总结下有key和没有key的区别。

二、React.Children.forEach()

跟React.Children.map()一样,区别在于无返回

function forEachChildren(
  children: ?ReactNodeList,
  forEachFunc: ForEachFunc,
  forEachContext: mixed,
): void {
  mapChildren(
    children,
    function() {
      forEachFunc.apply(this, arguments);
    },
    forEachContext,
  );
}

三、React.Children.count()

计算children的数量

function countChildren(children: ?ReactNodeList): number {
  let n = 0;
  mapChildren(children, () => {
    n++;
  });
  return n;
}

四、React.Children.only()

判断children是不是只有一个子节点,如果是,就返回这个children, 否则抛出一个错误。

function onlyChild<T>(children: T): T {
  invariant(
    isValidElement(children),
    'React.Children.only expected to receive a single React element child.',
  );
  return children;
}

五、React.Children.toArray()

将children转换成数组,之后就可以使用数组中的方法来操作children

function toArray(children: ?ReactNodeList): Array<React$Node> {
  return mapChildren(children, child => child) || [];
}

总结:

这5个函数除了 only 以外, 都是调用mapChildren这个方法遍历children的。了解其中map的操作,其他的就自然而然懂了。