挑战 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 引入刚刚写好的 UserGreetingimport 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 的例子没有举得很好,可以看以下官方网站範例。
小结论
自己比较常使用为第三种 - 三元运算符,更为简洁易读。