From 45aa59a6f014797773269c9bd38a65cb3af9d733 Mon Sep 17 00:00:00 2001 From: weilihua1 <282894821@qq.com> Date: Tue, 7 Apr 2020 11:58:44 +0800 Subject: [PATCH] update src/react/ReactChildren.js. --- src/react/ReactChildren.js | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d8..cfd3e1b 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,6 +1,38 @@ function mapChildren(children, func, context) { //TODO实现此mapChildren方法 - return children; + if (!Array.isArray(children)) children = [children]; + children = flattenArray(children, [], ':'); + // console.log(children) + let mappedChildren = []; + children.forEach((item, index) => { + // console.log(item, 'item'); + let resItem = flattenArray(func(item, index), [], '/', item.key); + mappedChildren.push(...resItem) + }); + // return mappedChildren; + return mappedChildren; +} +/* + .0/ + .$+key2+/ .$key2/ + [key4] .3:$key4/ +*/ + +function flattenArray(arr, res = [], split, key) { + // console.log(arr, 'arr') + if (!Array.isArray(arr)) res.push(arr); + arr.forEach((item, index) => { + // console.log(item, 'item') + if (key) { + if (item.key) item.key = `${key}${split}.$${item.key}` + else item.key = `${key}${split}.${index}` + } else { + if (item.key) item.key = `.$${item.key}` + else item.key = `.${index}` + } + Array.isArray(item) ? flattenArray(item, res, ':', item.key) : res.push(item); + }); + return res; } export { -- Gitee