From d909e31fa3411b8e502581f432d4eeda715c38ac Mon Sep 17 00:00:00 2001 From: sanqiqi <296250147@qq.com> Date: Tue, 7 Apr 2020 14:45:04 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=9E=E7=8E=B0=20React.Children.map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/react/ReactChildren.js | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d8..9e4d789 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 { -- Gitee