diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d81edaad3705a3dca0942e1cbc01bff2624..4dddcfea106219616f76ed48d0d4fc9ab80d50d4 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,6 +1,28 @@ function mapChildren(children, func, context) { - //TODO实现此mapChildren方法 - return children; + var result = []; + if (!Array.isArray(children)) children = [children]; + + function getKey(prefix, idx, has) { + var key = prefix + idx; + if (has) key += ":"; + return key; + } + function flatten(ary, prefix = ".") { + ary.forEach((item, idx) => { + if (Array.isArray(item)) flatten(item, getKey(prefix, idx, item.length > 1)); + else { + let temp = func.call(context, item, idx); + if (!Array.isArray(temp)) temp = [temp]; + temp.forEach((val, i) => { + let key = prefix + (item.key ? "$" + item.key : idx) + "/." + (val.key ? "$" + val.key : i); + val = cloneElement(val, { key }); + result.push(val); + }); + } + }); + } + flatten(children); + return result; } export {