[React组件封装][实例]懒加载切换视图组件

公众号:程序员波波

在开发过程中会遇到一种需求,就是在一块视图区域,可能需要根据不同的状态展示不同的组件。

但是如果单纯的只根据状态显示相应的组件,那么其他未显示组件的内部状态可能就无法保存了。

当然如果外部组件保存了它们所有组件的所需要的所有状态变量,那么就另当别论了。(scrollTop这类的状态可能保存起来比较麻烦)

所以想要封装一个组件。可以根据需求显示不同的组件,但是能维持组件的状态(也就是不显示的组件不被卸载)。

思路:

组件内部维护一个is_rendered字典,通过is_rendered来判断组件是否已经加载过,加载过的组件通过styles.hide来隐藏。如果没有加载的组件,而且不需要显示,那么就不加载该组件。

代码:

import React, {Component} from 'react';

const styles = {
    hide: {
        width: 0,
        height: 0,
        overflow: 'hidden',
    }
};

class LazySwapComponent extends Component {
    constructor(props) {
        super(props)

        this.is_rendered = {}
    }

    render() {
        const { currentIndex, ...others } = this.props
        let ans = []
        let index = 0
        React.Children.map(this.props.children, (children) => {
            if (index == currentIndex) {
                this.is_rendered[index] = true
            }
            if (this.is_rendered[index]) {
                if (index == currentIndex) {
                    ans.push(
                        <div key={index} {...others} >
                            {children}
                        </div>
                    )
                }
                else {
                    ans.push(
                        <div style={styles.hide} key={index} >
                            {children}
                        </div>
                    )
                }
            }
            else {
                ans.push(
                    <div style={styles.hide} key={index} ></div>
                )
            }
            index += 1
        })
        return ans;
    }
}

export default LazySwapComponent;

使用方法:

<LazySwapComponent
    className={styles.the_class}
    currentIndex={this.state.current_index}
>
    <Component1 />
    <Component2 />
</LazySwapComponent>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值