From e50f7e9d4092fa1054cf0ae16084e96ffcbdf2d6 Mon Sep 17 00:00:00 2001 From: Stella <1062878468@qq.com> Date: Tue, 7 Apr 2020 17:22:07 +0800 Subject: [PATCH] mapChildren done --- src/react/ReactChildren.js | 39 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d8..516fa26 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,8 +1,43 @@ +const SEPARATOR = '.'; +const SUBSEPARATOR = ':'; + function mapChildren(children, func, context) { - //TODO实现此mapChildren方法 - return children; + if (!children) return children; + let result = []; + + handleChildren(children, result, func) + + return result; } + +let prefixKey = SEPARATOR; +function handleChildren(children, result, func) { + if (Array.isArray(children)) { + children.forEach((item, index) => { + if (Array.isArray(item)) { + prefixKey = prefixKey + index + SUBSEPARATOR; + // iterate every props.child + handleChildren(item, result, func); + } else { + let child = func(item, index); + child.forEach(subChild => { + subChild.key = getComponentKey(item, index, subChild.key, item.key); + result.push(subChild); + }) + } + }) + } +} + +function getComponentKey(component, index, sourceKey, parentKey) { + if (typeof component === 'object' && component !== 'null' && parentKey != null) { + return prefixKey + '$' + parentKey + '/.$' + sourceKey; + } + return prefixKey + index + '/.$' + sourceKey; +} + + export { mapChildren as map, }; \ No newline at end of file -- Gitee