React:Conditional Rendering,条件渲染

就像JS中常常会根据条件(比如if/else、switch)返回不同的值,React中也可以根据组件的状态或其他参考条件返回不同的React Element。

比如根据用户是否登陆渲染对应的UI面板。

 1 class LoginControl extends React.Component {
 2   constructor(props) {
 3     super(props);
 4     this.handleLoginClick = this.handleLoginClick.bind(this);
 5     this.handleLogoutClick = this.handleLogoutClick.bind(this);
 6     this.state = {isLoggedIn: false};
 7   }
 8 
 9   handleLoginClick() {
10     this.setState({isLoggedIn: true});
11   }
12 
13   handleLogoutClick() {
14     this.setState({isLoggedIn: false});
15   }
16 
17   render() {
18     const isLoggedIn = this.state.isLoggedIn;
19 
20     let button = null;
21     if (isLoggedIn) {
22       button = <LogoutButton onClick={this.handleLogoutClick} />;
23     } else {
24       button = <LoginButton onClick={this.handleLoginClick} />;
25     }
26 
27     return (
28       <div>
29         <Greeting isLoggedIn={isLoggedIn} />
30         {button}
31       </div>
32     );
33   }
34 }
35 
36 ReactDOM.render(
37   <LoginControl />,
38   document.getElementById('root')
39 );

Class: constructor(props+state+binded-handler) + handler +render( return React Elements))

该结构中,只有render函数内用JSX最终输出React Elements。

inline-if:

可以用&&操作符 充当if,左边为真时再执行右边,否则跳过。

 1   return (
 2     <div>
 3       <h1>Hello!</h1>
 4       {unreadMessages.length > 0 &&
 5         <h2>
 6           You have {unreadMessages.length} unread messages.
 7         </h2>
 8       }
 9     </div>
10   );

inline-if-else:

1     <div>
2       The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
3     </div>

当条件比较复杂时,推荐将组件的模板拆分。

隐藏组件:

当希望组件隐藏时,让其返回null即可。不过这并不影响到生命周期函数的执行。 componentWillUpdatecomponentDidUpdate依然会被触发哦。

 1 function WarningBanner(props) {
 2   if (!props.warn) {
 3     return null;
 4   }
 5   //...
 6   render() {
 7     return (
 8       <div>
 9         <WarningBanner warn={this.state.showWarning} />
10         <button onClick={this.handleToggleClick}>
11           {this.state.showWarning ? 'Hide' : 'Show'}
12         </button>
13       </div>
14     );
15   //...