条件渲染

最后更新于:2022-04-02 03:33:39

[TOC] ## 简单demo ``` function Greeting(props) { const isLoggedIn = props.isLoggedIn; if (isLoggedIn) { return ; } return ; } ``` ## 与运算符 && > 在 JavaScript 中,`true && expression`总是会返回`expression`, 而`false && expression`总是会返回`false`。 ``` function Mailbox(props) { const unreadMessages = props.unreadMessages; return (

Hello!

{unreadMessages.length > 0 &&

You have {unreadMessages.length} unread messages.

}
); } const messages = ['React', 'Re: React', 'Re:Re: React']; ReactDOM.render( , document.getElementById('root') ); ``` ## 三目运算符 简单判断 ``` render() { const isLoggedIn = this.state.isLoggedIn; return (
The user is {isLoggedIn ? 'currently' : 'not'} logged in.
); } ``` 组件 ``` render() { const isLoggedIn = this.state.isLoggedIn; return (
{isLoggedIn ? ( ) : ( )}
); } ``` ## 阻止组件渲染 ``` function WarningBanner(props) { if (!props.warn) { return null; } return (
Warning!
); } ```
';