From 8443ce69de5c4bde0d6945efe057bb0813c35f27 Mon Sep 17 00:00:00 2001 From: gongchen Date: Wed, 8 Apr 2020 01:24:28 +0800 Subject: [PATCH] feat: mapChildren --- src/react/ReactChildren.js | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d8..98291ed 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,6 +1,34 @@ function mapChildren(children, func, context) { //TODO实现此mapChildren方法 - return children; + if (!children) { + return [] + } + let arr = [], idx = 0, key = '' + function fn(children) { + if (Array.isArray(children)) { + for (let i = 0; i < children.length; i++) { + let child = children[i]; + child.key == null ? key = `.${index}/$` : key = `.$${child.key}/.$`; + if (Array.isArray(child)) { + fn(child); + } else { + callback(child); + idx++; + } + } + } else { + callback([children]) + } + } + function callback(children) { + let o = func(children, idx); + for (let k = 0; k < o.length; k++) { + o[k].key = key + o[k].key; + arr.push(o[k]) + } + } + fn(children); + return arr; } export { -- Gitee