diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d81edaad3705a3dca0942e1cbc01bff2624..5fdef7256d6d3bb5308214eecd1301eecf42c074 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,6 +1,42 @@ function mapChildren(children, func, context) { //TODO实现此mapChildren方法 - return children; + // return children; + if (children === null) { + return children; + } + let array = [] + let result = [] + let index = 0 + getArray(children, array) + handleArray(result, array, func, context, index) + return result +} + +function getArray(children, array) { + if (Array.isArray(children)) { + children.forEach(ele => { + if (Array.isArray(ele)) { + return getArray(ele, array) + } + array.push(ele) + }) + } else { + array.push(children) + } +} + +function handleArray(result, array, func, context, index) { + for (let i = 0; i < array.length; i++) { + const item = array[i]; + const res = func.call(context, item, index++) + if (Array.isArray(res) && res.length) { + res.forEach(ele => { + result.push(ele) + }) + } else { + result.push(res) + } + } } export {