From 9d107dd1c0aa3adf3e39f4c1ad723900df64468d Mon Sep 17 00:00:00 2001 From: um-brella Date: Mon, 6 Apr 2020 14:39:33 +0800 Subject: [PATCH] =?UTF-8?q?#587#=E5=AE=9E=E7=8E=B0mapChildren=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/react/ReactChildren.js | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d8..b867e1e 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; } -- Gitee