diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d81edaad3705a3dca0942e1cbc01bff2624..5667b657b51f5006d4768bc4f0ee62840a5cc833 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,8 +1,48 @@ +/** @format */ +function getType(a) { + const str = Object.prototype.toString.call(a) + return /^\[object (.*)\]$/.exec(str)[1] +} + +function flat(children) { + return children.reduce((prev, cur) => { + return prev.concat(Array.isArray(cur) ? flat(cur) : cur) + }, []) +} + function mapChildren(children, func, context) { - //TODO实现此mapChildren方法 - return children; + let result = [] + + // 判断children类型 + console.group('mapChildren', children) + console.log('getType', getType(children)) + + if (typeof children !== 'object') { + result.push(children) + } + + if (getType(children) === 'Array') { + result = [...result, ...flat(children)] + } + + if (getType(children) === 'Object') { + if (children.props.children) { + return mapChildren(children.props.children, func, context) + } + } + // console.log('%cresult', 'color:red', result) + + result.forEach((item, index) => { + func.call(context, item, index) + }) + + result = result.map((item, index) => { + return func.call(context, item, index) + }) + + // console.groupEnd() + + return result } -export { - mapChildren as map, -}; \ No newline at end of file +export { mapChildren as map }