react学习笔记6--条件渲染

function UserGreeting(props) {
    return <h1>welcome back</h1>;
}
function GuestGreeting(props) {
    return <h1>pls. sign up</h1>;
}

function Greeting(props) {
    const isLoggerIn = props.isLoggerIn;
    if(isLoggerIn){
        return <UserGreeting />;
    }else {
        return <GuestGreeting />;
    }
}

ReactDOM.render(
    <Greeting isLoggerIn={false} />,
    document.getElementById('root')

);

可以使用变量来存储元素,可以避免在条件渲染的时候只渲染需要改变的元素

class LoginControl extends React.Component {
    constructor(props) {
        super(props);
        this.handleLoginClick = this.handleLoginClick.bind(this);
        this.handleLogoutClick = this.handleLogoutClick.bind(this);
        this.state = {isLoggerIn:false};
    }

    handleLoginClick() {
        this.setState({isLoggerIn:true});
    }

    handleLogoutClick() {
        this.setState({isLoggerIn:false});
    }

    render() {
        const isLoggerIn = this.state.isLoggerIn;
        let button;

        if(isLoggerIn) {
            button = <LogoutButton onClick={this.handleLogoutClick} />;
        }else{
            button = <LoginButton onClick={this.handleLoginClick} />;
        }

        return (
            <div>
                <Greeting isLoggerIn={isLoggerIn} />
                {button}
            </div>
        );

    }
}


ReactDOM.render(
    <LoginControl />,
    document.getElementById('root')
);

如果在一个JSX中嵌入javascript逻辑运算符&&,true && expression 会显示expression内容,如果是false && expression会忽略后面的表达式

function Mailbox(props) {
    const unreadMessages = props.unreadMessages;
    return (
        <div>
            <h1>hello</h1>
            {unreadMessages.length > 0 && 
                <h2>
                    you have {unreadMessages.length} unread messages
                </h2>
            }
        </div>
    );
}

const messages = ['react','re:react','re:re:react'];
ReactDOM.render(
    <Mailbox unreadMessages={messages} />,
    document.getElementById('root')
);

阻止组件渲染

function WarningBanner(props) {
    if(!props.warn) {
        return null;
    }
    return (
        <div className="warning">
            warning
        </div>
    );
}

class Page extends React.Component {
    constructor(props) {
        super(props);
        this.state = {showWarning:true};
        this.handleToggleClick = this.handleToggleClick.bind(this);
    }

    handleToggleClick() {
        this.setState(prevState => ({
            showWarning:!prevState.showWarning
        }));
    }

    render() {
        return (
            <div>
                <WarningBanner warn={this.state.showWarning} />
                <button onClick={this.handleToggleClick}>
                    {this.state.showWarning ? 'hide' : 'show'}
                </button>
            </div>
        );
    }
}

ReactDOM.render(
    <Page />,
    document.getElementById('root')

);

猜你喜欢

转载自blog.csdn.net/weixin_36926779/article/details/80981182