• React 组件条件渲染的几种方式


    一、条件表达式渲染 (适用于两个组件二选一的渲染)

     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 }

    二、&& 操作符渲染 (适用于一个组件有无的渲染)

     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 }

    三、利用变量输出组件渲染 (适用于有多个组件多种条件下的渲染)

     1 render() {
     2     const isLoggedIn = this.state.isLoggedIn;
     3     
     4     const button = isLoggedIn ? (
     5       <LogoutButton onClick={this.handleLogoutClick} />
     6     ) : (
     7       <LoginButton onClick={this.handleLoginClick} />
     8     );
     9 
    10     return (
    11       <div>
    12         <Greeting isLoggedIn={isLoggedIn} />
    13         {button}
    14       </div>
    15     );
    16   }

    四、利用函数方法输出组件或者利用函数式组件进行渲染 (适用于多个子组件需要根据复杂的条件输出的情况)

    1. 函数方式

     1 renderButton(){
     2     const isLoggedIn = this.state.isLoggedIn;
     3     if(isLoggedIn)
     4     {
     5        return (<LogoutButton onClick={this.handleLogoutClick} />);
     6     }
     7     else
     8     {
     9       return (<LoginButton onClick={this.handleLoginClick} />);
    10     }
    11 }
    12 
    13 render() {
    14     return (
    15       <div>
    16         <Greeting />
    17         {this.renderButton()}
    18       </div>
    19     );
    20   }

    2. 函数式组件

     1 function Greeting(props) {
     2   const isLoggedIn = props.isLoggedIn;
     3   if (isLoggedIn) {
     4     return <UserGreeting />;
     5   }
     6   return <GuestGreeting />;
     7 }
     8 
     9 ReactDOM.render(
    10   // Try changing to isLoggedIn={true}:
    11   <Greeting isLoggedIn={false} />,
    12   document.getElementById('root')
    13 );
  • 相关阅读:
    https进行配置以及http跳转到https配置
    centos7修改系统语言为简体中文
    iptables snat 和dnat说明
    python多线程执行类中的静态方法
    python 磁盘空间操作
    python logging 工具
    python 动态调用函数
    python 读写XML
    js加载json数据成表格
    python 比较两个数据库postgresql
  • 原文地址:https://www.cnblogs.com/xiaodi-js/p/9119826.html
Copyright © 2020-2023  润新知