React 条件渲染简单演示

前端开发 作者: 2024-08-19 21:05:01
模拟根据登录情况判断要显示的欢迎界面 import React, { Component } from 'react'; import ReactDOM from 'react
import React,{ Component } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import PropTypes from 'prop-types';

function Greeting(props){
  const state=props.state;

  if(state){
    return <UserGreeting />
  }else{
    return <GuestGreeting />
  }
}

 UserGreeting(){
  return (
    <div>欢迎用户</div>
  )
}

 GuestGreeting(){
   (
    <div>欢迎游客</div>
  )
}

  ReactDOM.render(
    <div>
      <Greeting state={false} />
    </div>,document.getElementById('example')
  );

serviceWorker.unregister();
import React,1)">;

class Logincontrol extends React.Component{
  constructor(props){
    super(props);
    this.logoutHandler=this.logoutHandler.bind(this);
    this.LoginHandler=this.LoginHandler.bind(this.state={
      loginState:false
    }
  }

  logoutHandler(){
    .setState({
      loginState:
    })
  }
  
  LoginHandler(){
    true
    })
  }

  render(){
    const loginState=.state.loginState;
    let button=null;
    if(loginState){//如果是登录状态
      button=<logoutBtn onClick={this.logoutHandler}/>
    }{
      button=<LoginBtn onClick={this.LoginHandler}/>
    }

    (
      <div>
        <p>登录状态:{this.state.loginState?'已登录':'未登录'}</p>
        {button} 
      </div>          
    )
  }
}

 logoutBtn(props){
  (
    <button onClick={props.onClick}>退出登录</button>
 LoginBtn(props){
  (
    <button onClick={props.onClick}>点击登录</button>
  )
}

  ReactDOM.render(
    <div>
      <Logincontrol />
    </div>,1)">)
  );

serviceWorker.unregister();
import React,1)"> Mail(props){
  const msg=props.msg;
  (
    <div>
    {
      msg.length>0 &&
      <p>共有{msg.length}条未读消息</p>
    }
    </div>
  )
}

const msg=[
  '下午有空吗?','明天有空吗?'
];

  ReactDOM.render(
    <div>
      <Mail msg={msg}/>
    </div>,1)">)
  );

serviceWorker.unregister();
import React,1)">;

class ShowWarning extends React.Component{
  constructor(props){
    super(props);
    this.showHide=this.showHide.bind({
      warningState:
    }
  }

  showHide(){
    this.setState(prevState=>({
      warningState:!prevState.warningState
    }))
  }
  
  hideHandler(){
    .setState({
      warningState:
    })
  }

  render(){

    (
      <div>
        <WarnBanner warn={this.state.warningState}/>
        <button onClick={this.showHide}>
          {this.state.warningState?'隐藏':'显示'}
        </button>
      </div>          
 WarnBanner(props){
  if(!props.warn){
    return 
  }(
      <div>警告警告!!!</div>
    )
  }
}

  ReactDOM.render(
    <div>
      <ShowWarning />
    </div>,1)">)
  );

serviceWorker.unregister();
this.setState((prevState,props) => ({
    do something here
}));

总结

原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_65144.html