最新的 react children 源码 方法简单实现

    const input = [1, 1]



        const map = (children, fc, context) => {

            let result = [];

            let count = 0;

            mapToArray(children, result, function (child) {

                return fc.call(context, child, count++);

            })

            return result;

        }



        const forEach = (children, fc, context) => {

            map(children, function () {

                fc.apply(this, arguments);

            }, context)

        }



        const count = (children) => {

            let count = 0;

            map(children, function () {

                count++;

            })

            return count;

        }



        const mapToArray = (children, result, fc) => {

            let invokeCallback = false;

            const type = typeof children;

            if (type === 'string' || type === 'boolean' || type === 'number') {

                invokeCallback = true;

            }

            if (invokeCallback) {

                let mappedChild = fc(children);

                console.log('mappedChild', mappedChild)

                if (mappedChild && mappedChild instanceof Array) {

                    mappedChild.forEach((c, index) => mapToArray(c, result, c => c));

                } else {

                    result && result.push(children);

                }

            }



            if (children instanceof Array) {

                children.forEach((c, index) => {

                    // console.log('---------------------', children)

                    mapToArray(c, result, fc)

                });

            }

        }



        console.log(map(input, (item, index) => {

            console.log(index)

            return [1, [

                [2, [5, 6], 3], 4

            ]]

        }));

        console.log(forEach(input, (item, index) => {

            console.log(index)

            return [1, [

                [2, [5, 6], 3], 4

            ]]

        }));

        console.log('count: ', count(input));

判断数组那里,还有可能是迭代器,原理都一样,就是遍历。

个人感觉, 通过修改回调的方式读起来会绕一些,在每个方法里面去遍历感觉会好一些,但是这样扩展起来好简单。

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值