diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d81edaad3705a3dca0942e1cbc01bff2624..a76766d977eacfb458249ca425b2ca32e86c1bd1 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