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