From 5a373a049e3a28968f46868ff6dc25f80303cb25 Mon Sep 17 00:00:00 2001 From: Simple <248200851@qq.com> Date: Mon, 6 Apr 2020 21:55:43 +0800 Subject: [PATCH] =?UTF-8?q?=E9=99=88=E6=97=AD=E4=B8=9C#772#?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/react/ReactChildren.js | 48 +++++++++++++++++++++++++++++++++++--- 1 file changed, 45 insertions(+), 3 deletions(-) diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d8..a76766d 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,8 +1,50 @@ +/** + * 主要处理key的后缀 + */ +function generateChildrenByFunc(child, index, func = c => [c]) { + const prefixKey = child.key; + let children = func(child, index); + if (Array.isArray(children)) { + return children.map((_child, i) => { + _child.key = _child.key ? `${prefixKey}/.$${_child.key}` : `${prefixKey}/.${i}` + return _child; + }); + } else { + children.key = children.key ? `${children.key}/${prefixKey}` : `${prefixKey}` + return [children]; + } +} + +/** + * 主要处理key的前缀 + */ +function traverseChildren(_children, index = 0, prefixKey, func = c => [c]) { + if (!Array.isArray(_children)) { + return null; + } + return _children.reduce((result, child, i) => { + const realIndex = index + i; + if (Array.isArray(child)) { + result.push(...traverseChildren(child, realIndex, `${prefixKey}${realIndex}:`, func)); + } else { + if (child.key) { + child.key = `${prefixKey}$${child.key}`; + } else { + child.key = `${prefixKey}${realIndex}`; + } + result.push(...generateChildrenByFunc(child, realIndex, func)); + } + return result; + }, []); + +} + function mapChildren(children, func, context) { - //TODO实现此mapChildren方法 - return children; + //TODO实现此mapChildren方法 + children = traverseChildren(children, 0, '.', func); + return children; } export { - mapChildren as map, + mapChildren as map, }; \ No newline at end of file -- Gitee