1、條件表達式渲染 (適用於兩個組件二選一的渲染)函數
1 render() { 2 const isLoggedIn = this.state.isLoggedIn; 3 return ( 4 <div> 5 {isLoggedIn ? ( 6 <LogoutButton onClick={this.handleLogoutClick} /> 7 ) : ( 8 <LoginButton onClick={this.handleLoginClick} /> 9 )} 10 </div> 11 ); 12 }
2、&& 操做符渲染 (適用於一個組件有無的渲染)this
1 function Mailbox(props) { 2 const unreadMessages = props.unreadMessages; 3 return ( 4 <div> 5 <h1>Hello!</h1> 6 {unreadMessages.length > 0 && 7 <h2> 8 You have {unreadMessages.length} unread messages. 9 </h2> 10 } 11 </div> 12 ); 13 }
3、利用變量輸出組件渲染 (適用於有多個組件多種條件下的渲染)spa
1 render() { 2 const isLoggedIn = this.state.isLoggedIn; 3 4 const button = isLoggedIn ? ( 5 <LogoutButton onClick={this.handleLogoutClick} /> 6 ) : ( 7 <LoginButton onClick={this.handleLoginClick} /> 8 ); 9 10 return ( 11 <div> 12 <Greeting isLoggedIn={isLoggedIn} /> 13 {button} 14 </div> 15 ); 16 }
4、利用函數方法輸出組件或者利用函數式組件進行渲染 (適用於多個子組件須要根據複雜的條件輸出的狀況)code
1. 函數方式blog
1 renderButton(){ 2 const isLoggedIn = this.state.isLoggedIn; 3 if(isLoggedIn) 4 { 5 return (<LogoutButton onClick={this.handleLogoutClick} />); 6 } 7 else 8 { 9 return (<LoginButton onClick={this.handleLoginClick} />); 10 } 11 } 12 13 render() { 14 return ( 15 <div> 16 <Greeting /> 17 {this.renderButton()} 18 </div> 19 ); 20 }
2. 函數式組件get
1 function Greeting(props) { 2 const isLoggedIn = props.isLoggedIn; 3 if (isLoggedIn) { 4 return <UserGreeting />; 5 } 6 return <GuestGreeting />; 7 } 8 9 ReactDOM.render( 10 // Try changing to isLoggedIn={true}: 11 <Greeting isLoggedIn={false} />, 12 document.getElementById('root') 13 );