From 5c830aed32f05e8e5ec101a6552df836c8a61dd7 Mon Sep 17 00:00:00 2001 From: "max.liu" <7415463+kelin418@user.noreply.gitee.com> Date: Mon, 6 Apr 2020 19:18:22 +0800 Subject: [PATCH] =?UTF-8?q?update=20src/react/ReactChildren.js.=20?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E7=AE=80=E6=98=93=E7=9A=84Children.map,?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E8=87=AA=E5=8A=A8=E7=94=9F=E6=88=90key.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/react/ReactChildren.js | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d8..4dddcfe 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,6 +1,28 @@ function mapChildren(children, func, context) { - //TODO实现此mapChildren方法 - return children; + var result = []; + if (!Array.isArray(children)) children = [children]; + + function getKey(prefix, idx, has) { + var key = prefix + idx; + if (has) key += ":"; + return key; + } + function flatten(ary, prefix = ".") { + ary.forEach((item, idx) => { + if (Array.isArray(item)) flatten(item, getKey(prefix, idx, item.length > 1)); + else { + let temp = func.call(context, item, idx); + if (!Array.isArray(temp)) temp = [temp]; + temp.forEach((val, i) => { + let key = prefix + (item.key ? "$" + item.key : idx) + "/." + (val.key ? "$" + val.key : i); + val = cloneElement(val, { key }); + result.push(val); + }); + } + }); + } + flatten(children); + return result; } export { -- Gitee