React学习笔记(七)条件渲染

React学习笔记(七)

六、条件渲染

使用if条件运算符来创建表示当前状态的元素。

  • 可以使用变量来存储元素。比如:
let button = null;
if (isLoggedIn) {
    button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
    button = <LoginButton onClick={this.handleLoginClick} />;
}
  • 与(&&)运算符

可以通过用花括号包裹代码在JSX中嵌入任何表达式。

function Mailbox(props) {
    const unreadMessages = props.unreadMessages;
    return (
        <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('root')
);

  • 三目运算符
render() {
    const isLoggedIn = this.state.isLoggedIn;
    return (
        <div>
            The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
        </div>
     );
}

  • 阻止组件渲染

render方法返回null就可以实现隐藏组件。
组件的render方法返回null并不会影响该组件生命周期方法的回调。

function WarnTip(props) {
  const isShow = props.isShow;
  if (!isShow) {
    return null;
  }
  
  return (
    <div className="wran-tip">FBI WARNING</div>
  );
}

class ToggleWarn extends React.Component {
  constructor(props) {
    super(props);
   
    this.state = {
      isShow: false
    };
  }
  
  render() {
    return (
      <div>
        <WarnTip isShow={this.state.isShow} />
        <button type="button" onClick={this.toggle.bind(this)}>
          { this.state.isShow ? 'Hide' : 'Show' }
        </button>
      </div>
    )
  }
  
  toggle() {
    this.setState(prev => ({
      isShow: !prev.isShow
    }));
  }
}

ReactDOM.render(
  <ToggleWarn />,
  document.getElementById('root')
);

The end... Last updated by: Jehorn, April 22, 2019, 3:32 PM

原文地址:https://www.cnblogs.com/jehorn/p/10750473.html