繁体   English   中英

有条件地渲染一个React组件

[英]Conditionally rendering a react component

对于在生命周期中某个时刻隐藏的组件,呈现它的最佳方法是什么? 1)渲染组件,但不显示它(display:none)。 2)仅在需要时渲染组件。 什么对性能更好? 如果组件的属性和状态稍后更新,那么将组件存在但隐藏在虚拟DOM中会更好吗?

render() {
    return (
        <div style={{display: this.props.visible ? 'block' : 'none'}}>
            <RestofComponentHere />
        </div>
    );
}

或这个:

render() {
    if (!this.props.visible) {
        return null;
    }
    return (
        <div>
            <RestofComponentHere />
        </div>
    );
}

只要选择最适合这种情况的方法即可。 有时是方法1,有时是方法2。如果您发现应用程序速度变慢,则转换为方法1相当容易,但这只有在有条件地渲染大量时间的情况下才应如此。 当您拥有对组件的引用时,您希望始终对其进行渲染,以便可以访问componentDidMount的引用,从而将其隐藏。

第一种方法是更快如图答案在这里 ,但没有为它的缘故做微的优化,如果有条件的渲染是更干净的代码。

我在我的应用程序中混合使用了。

我建议使用状态值,并根据状态值确定条件以决定要显示还是隐藏组件。

    constructor(props){
       //Set some initial condition for display depending on prop or default value
        //Something similar to this: 
        display: props.toDisplay === undefined ? true : props.toDisplay
    } 

    componentDidMount(){
        //update the state depending on the response or change
    } 

    onClick(event){
      //It might depend on someOther component's click action. 
    }

render方法将具有以下内容:

    render(){
       const toDisplay = this.state.display 
       if(toDisplay && 
        // Component To render
        )
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM