diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d81edaad3705a3dca0942e1cbc01bff2624..068ebb07fbffa42d4fe2ae8f2045432f676630c5 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,8 +1,49 @@ function mapChildren(children, func, context) { //TODO实现此mapChildren方法 - return children; + if (children == null) { + return children; + } + const result = []; + mapIntoWithKey(children, result, func, context); + return result; +} +function mapIntoWithKey (children, result, func, context) { + let arr =[]; + for (let i = 0; i < children.length; i++) { + if (Array.isArray(children[i])) { + children[i].map(item => { + item.fromArrayIndex = i; + arr.push(item) + }); + } else { + arr.push(children[i]); + } + } + arr.map((item, index) => { + const itemKey = item.key; + const fromArrayIndex = item.fromArrayIndex; + let newArr = func(item, index); + for (let i = 0; i < newArr.length; i++) { + newArr[i].key = concatKey(itemKey, newArr[i].key, index, fromArrayIndex); + } + result.push(...newArr); + }); +} +function isHave(x, index, fromArrayIndex) { + if (!fromArrayIndex) { + fromArrayIndex = ''; + } else { + fromArrayIndex = fromArrayIndex + ':'; + } + if (x) { + return '.' + fromArrayIndex + '$' + x; + } else { + return '.' + index; + } +} +function concatKey(a, b, index, fromArrayIndex) { + return isHave(a, index, fromArrayIndex) + '/' + isHave(b, index); } - export { mapChildren as map, }; \ No newline at end of file