React 官方文档所教的条件 Render

挑战 React 第十八篇

新年快乐!!
这是今年的第一篇,之后大概是一週新增一篇文章的节奏。

目标

isLogin 状态为登入,页面显示欢迎使用者 Tom;
isLogin 状态为登出,页面显示欢迎使用者 Guest。

前置作业

在 src 资料夹底下新增 UserGreeting.js 档案
import React, { Component } from 'react'class UserGreeting extends Component {  constructor(props) {    super(props)    // 预设为非登入状态    this.state = {       isLogin: false    }  }    render() {    return (      <div>        <div>        Welcome Guest!          </div>         <div>         Welcome Tom!          </div>      </div>    )  }}export default UserGreeting
App.js 引入刚刚写好的 UserGreeting
import React from 'react';import './App.css';import UserGreeting from './UserGreeting';function App() {  return (    <div className="App">      <UserGreeting />    </div>  );}export default App;
yarn start 成果

实作

以下会有四种写法:

if - else

特别注意,有些人可能想在 return 里面的讯息写 if - else,但这么做是不行的,因为 return 里写的是 jsx 。
jsx详细内容参考官网

render() {    if (this.state.isLogin) {      return <div> Welcome Tom!</div>    } else {        return <div> Welcome Guest!</div>    }  }
Element 变数
render() {    let message;    if (this.state.isLogin) {      message = <div>Welcome Tom!</div>    } else {      message = <div>Welcome Guest!</div>    }    return <div>{message}</div>  }
三元运算符
render() {    return (      this.state.isLogin ?      <div>Welcome Tom!</div> :      <div>Welcome Guest!</div>    )  }
Inline If 与 && 逻辑运算子

若为登入的情况,则显示 Welcome Tom,否则不会跳到右边那一段。

render() {    return (this.state.isLogin && <div>Welcome Tom!</div>)  }

使用 Inline if 的例子没有举得很好,可以看以下官方网站範例。

小结论

自己比较常使用为第三种 - 三元运算符,更为简洁易读。


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章