7. react 中的条件渲染

1. if 条件渲染

function UserGreeting (props) {
  return <h2>用户登录</h2>
}

function GuestGretting (props) {
  return <h2>游客登录</h2>
}

function Greeting (props) {
  const isLogin = props.isLogin
  if (isLogin) {
    return <UserGreeting />
  }
  return <GuestGretting />
}

ReactDOM.render(
  <Greeting isLogin={true} />,
  document.getElementById('root')
)

2. 事件控制 if 条件渲染

function UserGreeting (props) {
  return <h2>用户登录</h2>
}

function GuestGretting (props) {
  return <h2>游客登录</h2>
}

function Greeting (props) {
  const isLogin = props.isLogin
  if (isLogin) {
    return <UserGreeting />
  }
  return <GuestGretting />
}

class LoginControl extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      isLogin: false
    }
  }

  handleLoginIn () {
    this.setState({
      isLogin: true
    })
  }

  handleLoginOut () {
    this.setState({
      isLogin: false
    })
  }

  loginBtn () {
    if (this.state.isLogin) {
      return <button onClick={this.handleLoginOut.bind(this)}>退出</button>
    }
    return <button onClick={this.handleLoginIn.bind(this)}>登录</button>
  }

  render () {
    const isLogin = this.state.isLogin

    return (
      <div>
        {this.loginBtn()}
        <Greeting isLogin={isLogin} />
      </div>
    )
  }
}
ReactDOM.render(
  <LoginControl />,
  document.getElementById('root')
)

 

3. 与运算符 && 渲染

  1. 可以在 JSX 中嵌套任何表达式

  2. true && expression 总是会返回 expression, 而 false && expression 总是会返回 false

  

function UserGreeting (props) {
  return <h2>用户登录</h2>
}

function GuestGretting (props) {
  return <h2>游客登录</h2>
}
class LoginControl extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      isLogin: false
    }

    this.handleLoginIn = this.handleLoginIn.bind(this)
    this.handleLoginOut = this.handleLoginOut.bind(this)
  }

  handleLoginIn() {
    this.setState({
      isLogin: true
    })
  }

  handleLoginOut () {
    this.setState({
      isLogin: false
    })
  }

  render () {
    const isLogin = this.state.isLogin
    var btn = <button onClick={this.handleLoginIn}>登录</button>;
    if (isLogin) {
      btn = <button onClick={this.handleLoginOut}>退出</button>
    }
    return (
      <div>
        {btn}
        { isLogin && <UserGreeting />}  // 与运算条件渲染
      </div>
    )
  }
}
ReactDOM.render(
  <LoginControl />,
  document.getElementById('root')
)

 

4. 三目运算渲染   condition ? true : false

  上述实例改造为三目运算渲染

render () {
    const isLogin = this.state.isLogin
    var btn = <button onClick={this.handleLoginIn}>登录</button>;
    if (isLogin) {
      btn = <button onClick={this.handleLoginOut}>退出</button>
    }
    return (
      <div>
        {btn}
        { isLogin ? <UserGreeting /> : <GuestGretting />}   // 三目运算
      </div>
    )
  }
posted @ 2020-06-04 10:29  monkey-K  阅读(167)  评论(0编辑  收藏  举报