From 7f7240a3e59f6fb4a32448c45da31b79e27f4f64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E7=84=95?= Date: Mon, 6 Apr 2020 14:37:31 +0800 Subject: [PATCH] =?UTF-8?q?#437#=20React.Children.map=20=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/react/ReactChildren.js | 55 +++++++++++++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d8..9b61c60 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,8 +1,61 @@ function mapChildren(children, func, context) { + let result = []; + let count = 0; //TODO实现此mapChildren方法 - return children; + if (Array.isArray(children)) { // children是数组 + traverseArray(children, func, result, '', count); + } else { // children是个对象 + let replaceChildren = func(children, count++); + let parentKey = children.key; + if (!parentKey) { + parentKey = `.0/.`; + } else { + parentKey = `.$${parentKey}/.`; + } + result = flatReplace(replaceChildren, parentKey); + } + + return result; +} + +function traverseArray (array, func, result, prefix = '', count) { + for (let i = 0; i < array.length; i++) { + let item = array[i]; + if (Array.isArray(item)) { + traverseArray(item, func, result, `${i}:`, count); + } else { + item = { + ...item, + key: item.key ? `.${prefix}$${item.key}/.` : `.${prefix}${i}/.`, + } + let r = flatReplace(func(item, count++), item.key); + result.push(...r); + } + } } +function flatReplace(elements, parentKey) { + if(Array.isArray(elements)) { // 模板是数组 + elements = elements.flat().map((child, index) => { + let key = child.key; + if (!key) { + key = `${index}` + } else { + key = `$${key}` + } + key = parentKey + key; + return { + ...child, + key + } + }); + } else { + elements = flatReplace([elements], parentKey); + } + return elements; +} + + export { mapChildren as map, }; \ No newline at end of file -- Gitee