diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d81edaad3705a3dca0942e1cbc01bff2624..9e4d789bc1fbaf3ab08c917385a199a0d40ab758 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,6 +1,39 @@ +// 递归展平数组 +function spreadArray(arr) { + // 如果不是数组,就转化为数组,然后直接返回 + if (!Array.isArray(arr)) { + arr = [arr] + return arr + } + + // 把当前的这层展平 + return arr.reduce((prev, item) => { + return prev.concat(spreadArray(item)) + }, []) +} + function mapChildren(children, func, context) { - //TODO实现此mapChildren方法 - return children; + // 展平孩子数组 + children = spreadArray(children) + + // 遍历 + children = children.map((child, i) => { + // 记录孩子原来的 key + const oldChildKey = child.key ? `$${child.key}` : i + + // 执行 map 函数,并展平执行结果 + const funcResult = spreadArray(func(child, i)) + + return funcResult.map((newChild) => { + // 把 key 修改为合成之后的 + const newChildKey = newChild.key ? `$${newChild.key}` : i + newChild.key = `.${oldChildKey}/.${newChildKey}` + return newChild + }) + }) + + // 再次展平,并返回 + return spreadArray(children) } export {