zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    C# 不用添加WebService引用,调用WebService方法
    贪心 & 动态规划
    trie树 讲解 (转载)
    poj 2151 Check the difficulty of problems (检查问题的难度)
    poj 2513 Colored Sticks 彩色棒
    poj1442 Black Box 栈和优先队列
    啦啦啦
    poj 1265 Area(pick定理)
    poj 2418 Hardwood Species (trie树)
    poj 1836 Alignment 排队
  • 原文地址:https://www.cnblogs.com/jehorn/p/10750473.html
Copyright © 2011-2022 走看看