公众号:程序员波波
在开发过程中会遇到一种需求,就是在一块视图区域,可能需要根据不同的状态展示不同的组件。
但是如果单纯的只根据状态显示相应的组件,那么其他未显示组件的内部状态可能就无法保存了。
当然如果外部组件保存了它们所有组件的所需要的所有状态变量,那么就另当别论了。(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>