昨天和前天都是在介紹 components,所以今天依照課程安排進入 React components 的練習篇~
今天的課程就是把 index.js
裡的超長程式碼,都變成 components:
import React from "react";
import ReactDOM from "react-dom";
const date = new Date();
const currentTime = date.getHours();
let greeting;
const customStyle = {
color: ""
};
if (currentTime < 12) {
greeting = "Good Morning";
customStyle.color = "red";
} else if (currentTime < 18) {
greeting = "Good Afternoon";
customStyle.color = "green";
} else {
greeting = "Good Night";
customStyle.color = "blue";
}
ReactDOM.render(
<h1 className="heading" style={customStyle}>
{greeting}
</h1>,
document.getElementById("root")
);
最後期望的 index.js
檔案長這樣:
import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
ReactDOM.render(<App />, document.getElementById("root"));
我的想法是我會想分成兩個,一個是 App.jsx
用來執行所有 components,就像解答要求的那樣;另個是把 heading
做成一個 components。
按照邏輯順序的話,應該要先有 components,不然 App.jsx 就不知道要去哪裡找 components。
Heading.jsx:
import React from "react";
function Heading() {
const date = new Date();
const currentTime = date.getHours();
let greeting;
const customStyle = {
color: ""
};
if (currentTime < 12) {
greeting = "Good Morning";
customStyle.color = "red";
} else if (currentTime < 18) {
greeting = "Good Afternoon";
customStyle.color = "green";
} else {
greeting = "Good Night";
customStyle.color = "blue";
}
return (
<h1 className="heading" style={customStyle}>
{greeting}
</h1>
);
}
export default Heading;
其實以上就是把 ReactDOM.render
這邊改成 return
,然後把 document.getElementById("root")
拿掉,剩下的就是複製貼上。還有因為不用 document.getElementById("root")
所以不用 import react-dom
。
再來就是 App.jsx 檔案。
import React from "react";
import Heading from "./Heading";
function App() {
return (
<div>
<Heading />
</div>
);
}
export default App;
接著回到 index.js,把做好的 App.jsx 輸入在這個檔案中,還有要把 React.render
內容改為 App.jsx 的 function App ():
import App from "./components/App";
ReactDOM.render(<App />, document.getElementById("root"));
以上就是今天的練習題~