diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d81edaad3705a3dca0942e1cbc01bff2624..d8d84476aed95b67f38fd165bb3faa886f570e05 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,8 +1,61 @@ +import { REACT_ELEMENT_TYPE } from '../shared/ReactSymbols' + function mapChildren(children, func, context) { - //TODO实现此mapChildren方法 - return children; + const childArray = Array.isArray(children) ? children : [children] + const walkedChildren = walk(childArray, func); + return walkedChildren; +} + +/** + * + * @param {array} arr 子元素 + * @param {*} func + * @param {*} arrIndex 当前迭代的索引 + * @param {*} elementIndex 子元素索引 + */ +function walk(arr, func, arrIndex = 0, elementIndex = 0) { + return arr.reduce((collect, item, i) => { + // debugger + let res; + if (Array.isArray(item)) { + res = walk(item, func, arrIndex, elementIndex); + + } else { + res = func(item, elementIndex) + elementIndex++ + } + res = (Array.isArray(res) ? res : [res]).map(resItem => { + console.log(item.key); + + if (resItem.$$typeof === REACT_ELEMENT_TYPE) { + // 是react元素 + console.log(i, item.key, resItem.key); + let key = ''; + // 如果当前迭代元素是数组,加上数组索引 + if (Array.isArray(item)) { + key += `.${arrIndex}:` + } else if (item.key) { + // 如果迭代的元素有key则添加到迭代后的元素上 + key += `.$${item.key}` + } else { + key += `.${arrIndex}` + } + // 如果返回的元素有key追加 + if (resItem.key) { + key += `/.$${resItem.key}` + } + + resItem.key = key + } + return resItem + }) + + arrIndex++ + + return collect.concat(res) + }, []) } export { - mapChildren as map, -}; \ No newline at end of file + mapChildren as map, +}; \ No newline at end of file