Public Number: Programmer Bobo
There is a requirement in the development process, that is, in a view area, different components may need to be displayed according to different states.
However, if only the corresponding component is displayed according to the state, the internal state of other components that are not displayed may not be saved.
Of course, if external components hold all the state variables required by all of their components, that's another matter. (Status like scrollTop can be cumbersome to preserve)
So you want to encapsulate a component. Different components can be displayed as required, but the state of the component can be maintained (that is, components that are not displayed are not uninstalled).
Train of thought:
An is_rendered dictionary is maintained inside the component to determine whether the component has been loaded or not, and the loaded component is hidden by styles.hide. If there is no component loaded and no display is required, then the component is not loaded.
Code:
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;
Usage method:
<LazySwapComponent className={styles.the_class} currentIndex={this.state.current_index} > <Component1 /> <Component2 /> </LazySwapComponent>