From 2016817ac9b6c1e705814f004a4407cf9a6df372 Mon Sep 17 00:00:00 2001 From: lizhihua Date: Mon, 6 Apr 2020 11:22:42 +0800 Subject: [PATCH] =?UTF-8?q?2020.04.05=20=E5=AE=9E=E7=8E=B0=20ReactChildren?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/react/ReactChildren.js | 66 +++++++++++++++++++++++++++++++++++--- 1 file changed, 62 insertions(+), 4 deletions(-) diff --git a/src/react/ReactChildren.js b/src/react/ReactChildren.js index bbc07d8..068ee1d 100644 --- a/src/react/ReactChildren.js +++ b/src/react/ReactChildren.js @@ -1,8 +1,66 @@ -function mapChildren(children, func, context) { - //TODO实现此mapChildren方法 +import { REACT_ELEMENT_TYPE } from '../shared/ReactSymbols'; + +function mapIntoArray(children, array, callback) { + const type = typeof children; + + if (type === 'undefined' || type === 'boolean') { + children = null; + } + + let invokeCallback = false; + + if (children === null) { + invokeCallback = true; + } else { + switch (type) { + case 'string': + case 'number': + invokeCallback = true; + break; + case 'object': + switch (children.$$typeof) { + case REACT_ELEMENT_TYPE: + invokeCallback = true; + } + } + } + if (invokeCallback) { + const child = children; + let mappedChild = callback(child); + if (Array.isArray(mappedChild)) { + mappedChild.map(child => mapIntoArray(child, array, c => c)) + } else { + array.push(child) + } + } + if (Array.isArray(children)) { + for (let i = 0; i < children.length; i++) { + let child = children[i] + mapIntoArray( + child, + array, + callback, + ) + } + } +} + +function mapChildren( + children, + func, + context, +) { + if (children == null) { return children; + } + const result = []; + let count = 0; + mapIntoArray(children, result, function(child) { + return func.call(context, child, count++); + }); + return result; } export { - mapChildren as map, -}; \ No newline at end of file + mapChildren as map, +}; -- Gitee