实践 React 应用百问百答 〜02 计数器〜
首先
这篇文章是为了增加输出而乘坐@ Sicut_study发布的【React应用程序100个案例】系列的文章。
-
- 実装ルールや成果物の達成条件は元記事に従うものとします。
- 元記事との差別点として、具体的に自分がどんな実装を行ったのか(と必要に応じて解説)を記載します。
我打算跟随Sicut_study的100个项目,目标是学习React并持续100天。
本次原文在这里。
上一篇文章
請問有什麼問題嗎?
创建一个计数器
规则
引用自原始文章
-
- 主要なライブラリやフレームワークはReactである必要がありますが、その他のツールやライブラリ(例: Redux, Next.js, Styled Componentsなど)を組み合わせて使用することは自由
- TypeScriptを利用する
达到要求
从原文中引用
-
- 领域表示:存在数字显示区域。
-
- 增量按钮:点击此按钮,显示的数字将增加1。
-
- 减量按钮:点击此按钮,显示的数字将减少1。
-
- 初始显示:打开应用时数字为0。
- 状态管理:使用React的useState或useReducer来管理计数器的数字。
执行
我们将对上一次的应用程序进行编辑,并在App.tsx文件中实现。
如果使用useState
/** @jsxImportSource @emotion/react */
import { useState } from "react";
import { css } from "@emotion/react";
const App = () => {
// カウンターの状態を宣言
const [count, setCount] = useState(0);
const counterStyle = css`
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
height: 100vh;
text-align: center;
background-color: #282c34;
color: white;
font-size: 2rem;
`;
const buttonStyle = css`
padding: 10px 20px;
margin: 5px;
font-size: 1rem;
cursor: pointer;
`;
return (
<div css={counterStyle}>
<p>{count}</p>
<button css={buttonStyle} onClick={() => setCount(count + 1)}>
インクリメント
</button>
<button css={buttonStyle} onClick={() => setCount(count - 1)}>
デクリメント
</button>
</div>
);
};
export default App;
如果使用useReducer
/** @jsxImportSource @emotion/react */
import { useReducer } from "react";
import { css } from "@emotion/react";
// Stateの型を定義
type State = {
count: number;
};
// Actionの型を定義
type Action = { type: "increment" } | { type: "decrement" };
// 初期状態
const initialState: State = { count: 0 };
// リデューサー関数
function reducer(state: State, action: Action): State {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
throw new Error();
}
}
const App = () => {
// カウンターの状態を宣言
const [state, dispatch] = useReducer(reducer, initialState);
const counterStyle = css`
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
height: 100vh;
text-align: center;
background-color: #282c34;
color: white;
font-size: 2rem;
`;
const buttonStyle = css`
padding: 10px 20px;
margin: 5px;
font-size: 1rem;
cursor: pointer;
`;
return (
<div css={counterStyle}>
<p>{state.count}</p>
<button css={buttonStyle} onClick={() => dispatch({ type: "increment" })}>
インクリメント
</button>
<button css={buttonStyle} onClick={() => dispatch({ type: "decrement" })}>
デクリメント
</button>
</div>
);
};
export default App;
做完了
设计还有很大的改进空间,但已经满足了要求,因此在这里完成。
计数功能正常运行。

最后
我计划完成100个React应用的挑战,每个挑战都要进行100次。
如果你能支持我,我会非常高兴,希望能关注我。
我期待着你的赞和收藏。
再见。
下一篇文章