React基础—条件渲染

1. 条件渲染

React中有多种方式可以用于实现条件渲染,以根据状态置来显示不同的UI界面,下面分别对其进行介绍。

2. 分类

2.1 普通函数组件中的条件渲染

函数组件天然有利于编写js语句,可以很方便的用于返回所需的UI界面,比如下面的案例:

// 函数组件,条件返回
function Message(props) {
    
    
    if (props.isHuman) {
    
    
        return <p>Welcome!</p>
    }
    return <p>Error!</p>
}

class CondictionRender extends Component {
    
    
    render() {
    
    
        return (
            <div>
                <Message isHuman={
    
    false}/>
            </div>
        );
    }
}

2.2 类组件中使用变量来替换

类似的,可以在类组件的render函数中做一些前置的判断操作,然后具体需要渲染的布局内容存储在一个变量中,最后在return这个模板的时候就是存储的变量中的值决定。比如下面的代码:

class CondictionRender extends Component {
    
    
    isHuman = true
    render() {
    
    
        // 在render函数中进行前置判断
        let template
        if (this.isHuman) {
    
    
            template = <p>Welcome!</p>
        } else {
    
    
            template = <p>Error!</p>
        }
        return (
            <div>
                {
    
    template}
            </div>
        );
    }
}

2.3 使用&&运算符

class CondictionRender extends Component {
    
    
    isHuman = false

    render() {
    
    
        return (
            <div>
                {
    
    
                    this.isHuman && <p>Welcome!</p>
                }
                {
    
    
                    !this.isHuman && <p>Error!</p>
                }
            </div>
        );
    }
}

是因为在 JavaScript 中,true && expression总是会返回expression, 而false && expression总是会返回false。因此,如果条件是true&&右侧的元素就会被渲染,如果是falseReact 会忽略并跳过它。

2.4 使用三目运算符

class CondictionRender extends Component {
    
    
    isHuman = false

    render() {
    
    
        return (
            <div>
                {
    
    
                    this.isHuman ? <p>Welcome!</p> : <p>Error!</p>
                }
            </div>
        );
    }
}

猜你喜欢

转载自blog.csdn.net/qq_26460841/article/details/124992185