React 条件渲染
React笔记
元素变量
<body> <div id="example"></div> <script type="text/babel"> class LoginControl extends React.Component { constructor(props) { super(props); this.handleLoginClick = this.handleLoginClick.bind(this); this.handleLogoutClick = this.handleLogoutClick.bind(this); this.state = {isLoggedIn: false}; }
handleLoginClick() { this.setState({isLoggedIn: true}); }
handleLogoutClick() { this.setState({isLoggedIn: false}); }
render() { const isLoggedIn = this.state.isLoggedIn; let button;
if (isLoggedIn) { button = <LogoutButton onClick={this.handleLogoutClick} />; } else { button = <LoginButton onClick={this.handleLoginClick} />; }
return ( <div> <Greeting isLoggedIn={isLoggedIn} /> {button} </div> ); } }
function UserGreeting(props) { return <h1>给你一拳</h1>; }
function GuestGreeting(props) { return <h1>请先注册</h1>; }
function Greeting(props) { const isLoggedIn = props.isLoggedIn; if (isLoggedIn) { return <UserGreeting />; } return <GuestGreeting />; }
function LoginButton(props) { return ( <button onClick={props.onClick}> 注册 </button> ); }
function LogoutButton(props) { return ( <button onClick={props.onClick}> 退出 </button> ); }
ReactDOM.render( <LoginControl />, document.getElementById('example') ); </script> </body>
|
查看效果
与运算符 &&
true && expression 总是返回expression 而 false && expression 总是返回 false 条件是 true, && 右侧的元素就会被渲染 是 false会忽略
<body> <div id="example"></div> <script type="text/babel"> function Mailbox(props) { const unreadMessages = props.unreadMessages; return ( <div> <h1>我叫史迪奇</h1> {unreadMessages.length > 0 && <h2> 您浪费了{unreadMessages.length} 秒 </h2> } </div> ); }
const messages = ['React', 'Re: React', 'Re:Re: React']; ReactDOM.render( <Mailbox unreadMessages={messages} />, document.getElementById('example') ); </script> </body>
|
查看效果
三目运算符
阻止组件渲染
根据属性 warn 的值条件渲染 warn 的值是 false则组件不会渲染
<style> button { height: 40px; width: 200px; } .warning { background-color: red; text-align: center; width: 100%; padding: 10px;
font-size: 14pt; color: white; } </style> </head> <body> <div id="example"></div>
<script type="text/babel"> function WarningBanner(props) { if (!props.warn) { return null; }
return ( <div className="warning"> 给你一拳 </div> ); }
class Page extends React.Component { constructor(props) { super(props); this.state = {showWarning: true} this.handleToggleClick = this.handleToggleClick.bind(this); }
handleToggleClick() { this.setState(prevState => ({ showWarning: !prevState.showWarning })); } render() { return ( <div> <WarningBanner warn={this.state.showWarning} /> <button onClick={this.handleToggleClick}> {this.state.showWarning ? '刷新' : '点击'} </button> </div> ); } }
ReactDOM.render( <Page />, document.getElementById('example') ); </script> </body>
|
查看效果
作者: 我叫史迪奇
本文来自于:
https://sdq3.link/React-conditional-rendering.html博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议