From 595a45a321ed864b0628df0d5eb70b9f7d4ed63e Mon Sep 17 00:00:00 2001 From: wengyulin <244181866@qq.com> Date: Tue, 7 Apr 2020 13:22:26 +0800 Subject: [PATCH] weng --- src/react/ReactChildren.js | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d8..c291ffa 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,6 +1,38 @@ -function mapChildren(children, func, context) { +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