6、ReactJs基础知识06--条件渲染

1、函数式组件的条件渲染
      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 />;
      }
2、使用变量存储组件
function LoginButton(props) {
        return (
          <button onClick={props.onClick}>
            Login
          </button>
        );
      }

      function LogoutButton(props) {
        return (
          <button onClick={props.onClick}>
            Logout
          </button>
        );
      }
      class 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.isLoggedIn;
          // 此处变量用于存储不同的组件
          let button;

          if (isLoggedIn) {
            button = <LogoutButton onClick={this.handleLogoutClick} />;
          } else {
            button = <LoginButton onClick={this.handleLoginClick} />;
          }

          return (
            <div>
              <Greeting isLoggedIn={isLoggedIn} />
              {button}
            </div>
          );
        }
      }
3、使用与运算符 &&进行条件渲染
     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'];
    // 之所以能这样做,是因为在 JavaScript 中,true && expression 总是会返回 expression, 
      // 而 false && expression 总是会返回 false。
      // 因此,如果条件是 true,&& 右侧的元素就会被渲染,如果是 false,React 会忽略并跳过它。
4、三目运算符
   render() {
        const isLoggedIn = this.state.isLoggedIn;
        return (
          <div>
            {isLoggedIn ? (
              <LogoutButton onClick={this.handleLogoutClick} />
            ) : (
              <LoginButton onClick={this.handleLoginClick} />
            )}
          </div>
        );
      }
5、函数组件返回return null将会阻止组件的渲染
在组件的 render 方法中返回 null 并不会影响组件的生命周期,componentDidUpdate 依然会被调用
 
 
 
原文地址:https://www.cnblogs.com/gopark/p/12292491.html