1、条件判断if

  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. handleLoginClick() {
  9. this.setState({isLoggedIn: true});
  10. }
  11. handleLogoutClick() {
  12. this.setState({isLoggedIn: false});
  13. }
  14. render() {
  15. const isLoggedIn = this.state.isLoggedIn;
  16. let button;
  17. if (isLoggedIn) {
  18. button = <LogoutButton onClick={this.handleLogoutClick} />;
  19. } else {
  20. button = <LoginButton onClick={this.handleLoginClick} />;
  21. }
  22. return (
  23. <div>
  24. <Greeting isLoggedIn={isLoggedIn} />
  25. {button}
  26. </div>
  27. );
  28. }
  29. }
  30. ReactDOM.render(
  31. <LoginControl />,
  32. document.getElementById('root')
  33. );

2、与运算符 &&

  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. }
  14. const messages = ['React', 'Re: React', 'Re:Re: React'];
  15. ReactDOM.render(
  16. <Mailbox unreadMessages={messages} />,
  17. document.getElementById('root')
  18. );

3、三目运算符

三目运算符 [condition ? true : false](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)

  1. render() {
  2. const isLoggedIn = this.state.isLoggedIn;
  3. return (
  4. <div>
  5. The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
  6. </div>
  7. );
  8. }
  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. }