diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d81edaad3705a3dca0942e1cbc01bff2624..26250e296a999b3a40f2cd19ab43b1bc3627769e 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,8 +1,47 @@ function mapChildren(children, func, context) { //TODO实现此mapChildren方法 - return children; + if (children === null) { + return children; + } + let array = [] + let result = [] + let index = 0 + getChildArray(children, array) + handleChildArray(result, array, func, context, index) + return result } +//获取儿子组件数组 +function getChildArray(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 handleChildArray(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 { mapChildren as map, }; \ No newline at end of file