diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d81edaad3705a3dca0942e1cbc01bff2624..4cefd7608fc839d7f0864e0316e5ff94d1c0e02f 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,6 +1,23 @@ +import { cloneElement } from "react"; + function mapChildren(children, func, context) { //TODO实现此mapChildren方法 - return children; + // key 格式 .0/.$div0A | .$key2/.$div1A | .3:$key4/.$div3A + // .[原来的 key,没有就使用 index]/.$[现在的 key],如果是嵌套的则为 .[索引]:$[原来的key,没有就使用索引]/.$[现在的 key] + function recursion(items, pId) { + return items.map((it, index) => { + if (Array.isArray(it)) { + return recursion(it, !pId ? index : pId+':'+index) + } else { + let curIndex = children.flat(Infinity).findIndex(cur => cur.key === it.key) + return func(it, curIndex).map((i) => cloneElement(it, { + key: `.${!pId ? '' : pId + ':'}${it.key ? '$' + it.key : pId}/.$${i.key}` + }) + ) + } + }) + } + return recursion(children, 0).flat(Infinity) } export {