就像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 =;23 } else {24 button = ;25 }26 27 return (28 2932 );33 }34 }35 36 ReactDOM.render(3730 {button}31 ,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 ( 2310 );Hello!
4 {unreadMessages.length > 0 && 56 You have {unreadMessages.length} unread messages. 7
8 } 9
inline-if-else:
12 The user is {isLoggedIn ? 'currently' : 'not'} logged in.3
当条件比较复杂时,推荐将组件的模板拆分。
隐藏组件:
当希望组件隐藏时,让其返回null即可。不过这并不影响到生命周期函数的执行。 componentWillUpdate
和componentDidUpdate
依然会被触发哦。
1 function WarningBanner(props) { 2 if (!props.warn) { 3 return null; 4 } 5 //... 6 render() { 7 return ( 8914 );15 //...10 13