美文网首页
2-4 条件渲染

2-4 条件渲染

作者: bestCindy | 来源:发表于2020-07-20 23:18 被阅读0次

通过 JavaScript 中,条件运算,如 if…else…,三元运算符

1、直接通过条件运算返回要渲染的 JSX 对象

import React from 'react';
import ReactDOM from 'react-dom';

function UserGreet(props) {
    return (<h1>欢迎登陆</h1>)
}

function UserLogin(props) {
    return (<h1>请先登录</h1>)
}

class ParentCom extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLogin: true
        }
    }

    render() {
        if (this.state.isLogin) {
            return (<UserGreet></UserGreet>);
        } else {
            return (<UserLogin></UserLogin>)
        }
    }
}

ReactDOM.render(<ParentCom />, document.querySelector("#root"));

2、通过条件运算得出 JSX 对象,再将 JSX 对象渲染到模板中

import React from 'react';
import ReactDOM from 'react-dom';

function UserGreet(props) {
    return (<h1>欢迎登陆</h1>)
}

function UserLogin(props) {
    return (<h1>请先登录</h1>)
}

class ParentCom extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLogin: true
        }
    }

    render() {
        let element = null;
        if (this.state.isLogin) {
            element = <UserGreet></UserGreet>;
        } else {
            element = <UserLogin></UserLogin>;
        };

        return(
            <div>
                <h1>这是头部</h1>
                { element }
                <h1>这是三元运算符的操作</h1>
                { this.state.isLogin ?  <UserGreet></UserGreet> : <UserLogin></UserLogin> }
                <h1>这是尾部</h1>
            </div>
        )
    }
}

ReactDOM.render(<ParentCom />, document.querySelector("#root"));

相关文章

  • 2-4 条件渲染

    通过 JavaScript 中,条件运算,如 if…else…,三元运算符 1、直接通过条件运算返回要渲染的 JS...

  • 条件渲染

    条件渲染