使用if
或條件運算符
來建立表示當前狀態的元素。javascript
let button = null; if (isLoggedIn) { button = <LogoutButton onClick={this.handleLogoutClick} />; } else { button = <LoginButton onClick={this.handleLoginClick} />; }
能夠經過用花括號包裹代碼在JSX中嵌入任何表達式。java
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') );
render() { const isLoggedIn = this.state.isLoggedIn; return ( <div> The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in. </div> ); }
讓render
方法返回null
就能夠實現隱藏組件。
組件的render
方法返回null
並不會影響該組件生命週期方法的回調。react
function WarnTip(props) { const isShow = props.isShow; if (!isShow) { return null; } return ( <div className="wran-tip">FBI WARNING</div> ); } class ToggleWarn extends React.Component { constructor(props) { super(props); this.state = { isShow: false }; } render() { return ( <div> <WarnTip isShow={this.state.isShow} /> <button type="button" onClick={this.toggle.bind(this)}> { this.state.isShow ? 'Hide' : 'Show' } </button> </div> ) } toggle() { this.setState(prev => ({ isShow: !prev.isShow })); } } ReactDOM.render( <ToggleWarn />, document.getElementById('root') );
The end... Last updated by: Jehorn, April 22, 2019, 3:32 PMide