diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d81edaad3705a3dca0942e1cbc01bff2624..b867e1ec506c203776addc96ef5711ef6d87f6f7 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,5 +1,40 @@ function mapChildren(children, func, context) { //TODO实现此mapChildren方法 + if (typeof children === 'number' || typeof children === 'string') { + children = newMap([children], func) + } else if (typeof children === 'boolean') { + children = newMap([null], func) + } else if (Array.isArray(children)) { + children = newMap(replaceKey(children), func) + } + function replaceKey(array, space = '', last = '') { + const newArray = array.map((item, index) => { + let newKey = `${last}${last ? '/' : ''}.${space}${space ? ':' : ''}` + if (item && item.key) { + newKey = `${newKey}$${item.key}` + } else { + newKey = `${newKey}${index}` + } + if (Array.isArray(item)) { + return replaceKey(item, index) + } + return { + ...item, + key: newKey, + } + }) + return newArray.flat(Infinity) + } + function newMap(array, fn) { + const newArray = array.map((item, index) => { + const fnArray = fn(item, index) + if (Array.isArray(fnArray)) { + return replaceKey(fnArray, '', item && item.key ? item.key : `.${index}`) + } + return replaceKey([fnArray], '', item && item.key ? item.key : `.${index}`) + }) + return newArray.flat(Infinity) + } return children; }