1、示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
function UserGreeting (props) { return <h1>Welcome back!</h1> } function GuestGreeting (props) { return <h1>Please sign up.</h1> } function Greeting (props) { const isLoggedIn = props.isLoggedIn if (isLoggedIn) { return <UserGreeting /> } return <GuestGreeting /> } ReactDOM.render( <Greeting isLoggedIn={ false } />, document.getElementById('root') ) |
2、元素变量
- 使用变量存储元素,可以帮助按条件渲染组件的一部分
- 创建两个组件:登录和注销
123456789101112131415function LoginButton (props) {return (<button onClick={ props.onClick }>Login</button>)}function LogoutButton (props) {return (<button onClick={ props.onClick }>Logout</button>)} - 创建一个有状态的组件:
LoginControl
1234567891011121314151617181920212223242526272829303132333435363738394041424344class 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.isLoggedInlet buttonif (isLoggedIn) {button = <LogoutButton onClick={ this.handleLogoutClick } />} else {button = <LoginButton onClick={ this.handleLoginClick } />}return (<div><Greeting isLoggedIn={ isLoggedIn } />{ button }</div>)}}ReactDOM.render(<LoginControl />,document.getElementById('root2')) - 运行效果
3、与运算符 &&
- 通过花括号包裹代码,可以在 JSX 中嵌入任何表达式
- 逻辑与(&&)
- 示例:
1234567891011121314151617181920function Mailbox (props) {const unreadMessages = props.unreadMessagesreturn (<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('root3'))
4、三目运算符
condition ? true : false
- 示例1
12345678render() {const isLoggedIn = this.state.isLoggedIn;return (<div>The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.</div>)} - 示例2
1234567891011render() {const isLoggedIn = this.state.isLoggedIn;return (<div>{isLoggedIn? <LogoutButton onClick={this.handleLogoutClick} />: <LoginButton onClick={this.handleLoginClick} />}</div>)}
5、阻止组件渲染
render
方法直接返回null
,不进行任何渲染
1234567891011121314151617181920212223242526272829303132333435363738394041function WarningBanner (props) {if (!props.warn) {return null}return (<div className="warning">Warning!</div>)}class Page extends React.Component {constructor (props) {super(props)this.state = { showWarning: true }this.handleToggleClick = this.handleToggleClick.bind(this)}handleToggleClick() {this.setState(state => ({showWarning: !state.showWarning}))}render () {return (<div><WarningBanner warn={ this.state.showWarning } /><button onClick={ this.handleToggleClick }>{ this.state.showWarning ? 'Hide' : 'Show' }</button></div>)}}ReactDOM.render(<Page />,document.getElementById('root4'))