我們要將 useReducer 中看板的 state 顯示出來。首先在 src/components 資料夾中新增 Board 資料夾,然後在 Board 資料夾底下新增名稱為 Board.js 的檔案以及 Board.module.scss 的樣式檔案:
import React from "react";
import styles from "./Board.module.scss";
const Board = props => {
return (
<div className={styles.board}>
<h2 className={styles.name}>
{props.name}
</h2>
</div>
);
};
.board {
margin-right: 8px;
border-radius: 4px;
width: 320px;
background-color: darkgray;
display: flex;
flex-direction: column;
padding: 8px;
flex-shrink: 0;
position: relative;
.name {
padding: 8px;
cursor: pointer;
width: 50%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
&:hover {
text-decoration: underline;
}
}
}
其中先準備好從 props 中取得看板的名稱 name 並且顯示出來。
建好 Board 元件之後,我們就可以在 App 元件中來使用它,並且傳入看板名稱:
import React from "react";
import { reducer, initialState } from "./reducer";
import AddBoard from "../AddBoard/AddBoard";
import styles from "./App.module.scss";
// 引用 Board 元件
import Board from "../Board/Board";
const App = () => {
const [state, dispatch] = React.useReducer(reducer, initialState);
const [isEditingTitle, setIsEditingTitle] = React.useState(false);
React.useEffect(() => {
document.title = state.title;
}, [state.title]);
return (
<div className={styles.app}>
{isEditingTitle ? (
<input
className={styles.titleInput}
value={state.title}
onChange={e => {
dispatch({
type: "CHANGE_TITLE",
payload: {
title: e.target.value
}
});
}}
onKeyPress={e => {
if (e.key === "Enter") {
setIsEditingTitle(false);
}
}}
autoFocus
/>
) : (
<h1 className={styles.title} onClick={() => setIsEditingTitle(true)}>
{state.title}
</h1>
)}
<div className={styles.boards}>
{state.boards.ids.map((id, index) => (
<Board
key={id}
// 傳入看板名稱
name={state.boards.byId[id].name}
/>
))}
<AddBoard />
</div>
</div>
);
};
export default App;
加入刪除看板與編輯看板名稱的功能。