diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d81edaad3705a3dca0942e1cbc01bff2624..516fa268daa893ff8d158aca5a42813e61752463 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