react children提供的5个API

react children提供的5个API:forEach、map、count、only、toArray

核心实现函数源码:

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;
        }
    }
  }

  if (invokeCallback) { // 子元素不为数组,为简单元素情况
    const child = children;
    let mappedChild = callback(child);  // 执行用户传入的function,不一定是c => c,有可能执行后是多维数组
    // If it's the only child, treat the name as if it was wrapped in an array
    // so that it's consistent if the number of children grows:
    const childKey =
      nameSoFar === '' ? SEPARATOR + getElementKey(child, 0) : nameSoFar;
    if (Array.isArray(mappedChild)) {
      let escapedChildKey = '';
      if (childKey != null) {
        escapedChildKey = escapeUserProvidedKey(childKey) + '/';
      }
      mapIntoArray(mappedChild, array, escapedChildKey, '', c => c); // 递归执行
    } else if (mappedChild != null) {
      if (isValidElement(mappedChild)) { // 判断是不是REACT_ELEMENT_TYPE元素
        mappedChild = cloneAndReplaceKey( // 根据旧节点克隆元素,替换为新的key
          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,
        );
      }
      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;

  if (Array.isArray(children)) {
    for (let i = 0; i < children.length; i++) {
      child = children[i];
      nextName = nextNamePrefix + getElementKey(child, i);
      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;
}
function mapChildren(
  children: ?ReactNodeList,
  func: MapFunc,
  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;
}
function countChildren(children: ?ReactNodeList): number {
  let n = 0;
  mapChildren(children, () => {
    n++;
    // Don't return anything
  });
  return n;
}
function forEachChildren(
  children: ?ReactNodeList,
  forEachFunc: ForEachFunc,
  forEachContext: mixed,
): void {
  mapChildren(
    children,
    function() {
      forEachFunc.apply(this, arguments);
      // Don't return anything.
    },
    forEachContext,
  );
}
function toArray(children: ?ReactNodeList): Array<React$Node> {
  return mapChildren(children, child => child) || [];
}
function onlyChild<T>(children: T): T {
  invariant(
    isValidElement(children),
    'React.Children.only expected to receive a single React element child.',
  );
  return children;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React是一个庞大的库,包含了许多API和功能。以下是React的全部API: 1. ReactReact的顶级命名空间。 2. React.Component:React组件的基类,用于定义新的组件。 3. React.PureComponent:类似于React.Component,但是实现了浅比较,用于优化性能。 4. React.createElement():用于创建React元素。 5. React.cloneElement():用于克隆React元素。 6. React.createFactory():用于创建工厂函数,用于创建React元素。 7. React.isValidElement():用于检查对象是否为React元素。 8. React.Children:用于处理React元素的子元素。 9. React.createRef():用于创建一个ref。 10. React.forwardRef():用于将ref转发到子组件。 11. React.Component.prototype.setState():用于更新组件的状态。 12. React.Component.prototype.forceUpdate():用于强制组件重新渲染。 13. React.Component.prototype.render():用于返回组件的视图。 14. React.Component.prototype.componentDidMount():组件挂载到DOM后调用的方法。 15. React.Component.prototype.componentDidUpdate():组件更新后调用的方法。 16. React.Component.prototype.componentWillUnmount():组件从DOM卸载前调用的方法。 17. React.Component.prototype.shouldComponentUpdate():决定组件是否需要重新渲染的方法。 18. React.Component.prototype.getSnapshotBeforeUpdate():在组件更新前获取DOM快照的方法。 19. React.createContext():创建一个Context对象。 20. React.useContext():用于获取Context中的值。 21. React.createPortal():用于将组件渲染到其他地方。 22. React.lazy():用于懒加载组件。 23. React.Suspense:用于处理懒加载组件的加载状态。 24. React.memo():用于优化组件性能的高阶组件。 25. React.useCallback():用于缓存函数的hook。 26. React.useEffect():用于处理副作用的hook。 27. React.useLayoutEffect():类似于useEffect,但会在DOM更新前同步执行。 28. React.useMemo():用于缓存计算结果的hook。 29. React.useReducer():用于处理复杂状态的hook。 30. React.useRef():用于创建一个ref的hook。 31. React.useState():用于管理组件状态的hook。 32. React.version:React的版本号。 这些API涵盖了React的许多方面,从基础的元素创建到高级的钩子处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值