2019年9月25日 星期三

[React] Functional Component


import React from 'react'

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 />
}

export default Greeting;


Github連結


import React, { Component } from 'react'
import LoginGreeting from './LoginGreeting'


function LogoutButton(props) {
    return (
        <button onClick={ props.onClick }>
            Logout
        </button>
    )
}

function LoginButton(props) {
    return (
        <button onClick={ props.onClick }>
            Login
        </button>
    )
}

export class LoginControl extends 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 }></LogoutButton>
        }else{
            button = <LoginButton onClick={ this.handleLoginClick }></LoginButton>
        }

        return (
            <div>
                <LoginGreeting isLoggedIn={ isLoggedIn } />
                { button }
            </div>
        )
    }
}

export default LoginControl


Github連結


沒有留言:

張貼留言