今天的練習題目是:
//Create a React app from scratch.
//Show a single h1 that says "Good morning" if between midnight and 12PM.
//or "Good Afternoon" if between 12PM and 6PM.
//or "Good evening" if between 6PM and midnight.
//Apply the "heading" style in the styles.css
//Dynamically change the color of the h1 using inline css styles.
//Morning = red, Afternoon = green, Night = blue.
我對於題目的想法是,我會先把會變動的變數先做好,再來是的邏輯。這樣在做邏輯時才知道要放入哪些變數。
目前想到的變數會有:{greetingWords}、{color}、{hours}
邏輯:
midnight ~ 12 PM = Good morning
12 PM ~ 6 PM = Good Afternoon
6 PM ~ midnight = Good evening
「每小時」則是參考 w3schools 的說明:
Get the hours:
const d = new Date();
let hour = d.getHours();
目前的變數:
const date = new Date();
const currentTime = date.getHours();
let greetingWords = 'good something';
const customColor = {
color:""
};
{greetingWords}、{color}、{hours} 都有了~
0 ~ 12 = Good morning => 現在 < 12 點
12 ~ 18 = Good Afternoon => 現在 < 18 點
18 ~ 0 = Good evening => 沒有符合以上條件都算這個
if (currentTime < 12 ){
greetingWords = 'Good Morning'
}else if (currentTime < 18) {
greetingWords = "Good Afternoon";
}else{
greetingWords = "Good Evening";
}
呼,覺得這比前面容易多了,現在只要加上顏色變化就好。
0 ~ 12 = Good morning => 現在 < 12 點 + Morning = red
12 ~ 18 = Good Afternoon => 現在 < 18 點 + Afternoon = green
18 ~ 0 = Good evening => 沒有符合以上條件都算這個 + Night = blue
if (currentTime < 12 ){
greetingWords = 'Good Morning';
customColor.color="red";
}else if (currentTime < 18) {
greetingWords = "Good Afternoon";
customColor.color="green";
}else{
greetingWords = "Good Evening";
customColor.color="blue";
}
回頭看一下題目,看看是否都有達成:
Y - //Create a React app from scratch.
Y - //Show a single h1 that says "Good morning" if between midnight and 12PM.
Y - //or "Good Afternoon" if between 12PM and 6PM.
Y - //or "Good evening" if between 6PM and midnight.
Y - //Apply the "heading" style in the styles.css
Y - //Dynamically change the color of the h1 using inline css styles.
Y - //Morning = red, Afternoon = green, Night = blue.
完成的 JXS:
//Create a React app from scratch.
//Show a single h1 that says "Good morning" if between midnight and 12PM.
//or "Good Afternoon" if between 12PM and 6PM.
//or "Good evening" if between 6PM and midnight.
//Apply the "heading" style in the styles.css
//Dynamically change the color of the h1 using inline css styles.
//Morning = red, Afternoon = green, Night = blue.
import React from "react";
import ReactDOM from "react-dom";
const date = new Date();
const currentTime = date.getHours();
let greetingWords = 'good something';
const customColor = {
color:""
};
if (currentTime < 12 ){
greetingWords = 'Good Morning';
customColor.color="red";
}else if (currentTime < 18) {
greetingWords = "Good Afternoon";
customColor.color="green";
}else{
greetingWords = "Good Evening";
customColor.color="blue";
}
ReactDOM.render(
<h1 className="heading" style={customColor}>
{greetingWords}
</h1>,
document.getElementById("root")
);
一開局就有附上的 styles.css:
.heading {
font-size: 50px;
font-weight: bold;
border-bottom: 5px solid black;
}