From b2c532f4cab86115e075c5b235d7ba026b41bb56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E7=88=B1=E5=86=9B?= Date: Mon, 6 Apr 2020 20:23:19 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=98=E7=88=B1=E5=86=9B#710#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/react/ReactChildren.js | 38 +++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d8..5fdef72 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 { -- Gitee