首頁  >  文章  >  web前端  >  用 React 建立一個簡單的計算器

用 React 建立一個簡單的計算器

王林
王林原創
2024-09-04 07:03:02757瀏覽

Building a Simple Calculator with React

介紹

在本教學中,我們將引導您使用 React 建立一個簡單且實用的計算器。對於希望獲得 React 實務經驗並了解如何在 React 應用程式中管理狀態和處理事件的初學者來說,該專案是一個很好的起點。

項目概況

這個計算器項目允許使用者執行基本算術運算,如加法、減法、乘法和除法。該計算器具有時尚、用戶友好的介面,它可以處理所有基本操作,包括清除輸入、刪除最後輸入的值以及計算結果。

特徵

  • 基本算術運算:支援加減乘除。
  • 清除(AC)和刪除(DEL)功能:輕鬆清除所有輸入或刪除最後輸入的數字。
  • 響應式設計:適用於各種螢幕尺寸,具有直覺的按鈕佈局。
  • 錯誤處理:如果執行無效操作,則顯示錯誤訊息。

使用的技術

  • React:用於建立使用者介面。
  • CSS:用於設計應用程式樣式並確保響應式設計。

專案結構

專案的架構如下:

├── public
├── src
│   ├── components
│   │   └── Calculator.jsx
│   ├── App.jsx
│   ├── App.css
│   ├── index.js
│   └── index.css
├── package.json
└── README.md

關鍵零件

  • Calculator.jsx:包含計算器的主要邏輯,包括狀態管理和事件處理。
  • App.jsx:包裝計算器元件並處理應用程式的整體佈局。
  • App.css:包含計算器元件的樣式。

程式碼說明

計算機組件

計算器元件使用 useState 掛鉤管理計算器輸入和結果的狀態。它包括一個handleClick 函數,用於處理按鈕單擊並相應地更新狀態。 calculateResult 函數使用 JavaScript 的 eval 函數評估輸入並更新結果。

import  { useState } from "react";

const Calculator = () => {
  const [input, setInput] = useState("");
  const [result, setResult] = useState("");

  const handleClick = (value) => {
    if (value === "AC") {
      setInput("");
      setResult("");
    } else if (value === "DEL") {
      setInput(input.slice(0, -1));
    } else if (value === "=") {
        setResult("")
      calculateResult();
    } else {
      setInput(input + value);
    }
  };

  const calculateResult = () => {
    try {
      setInput(eval(input));
    } catch (error) {
      setResult("Enter Valid Operation");
    }
  };

  return (
    <div className="calculator">
      <div className="output-box">
        <h1>{input}</h1>
        <h2>{result}</h2>
      </div>
      <div className="buttons">
        <div className="row-1">
          <button onClick={() => handleClick("AC")}>
            <p>AC</p>
          </button>
          <button onClick={() => handleClick("DEL")}>
            <p>DEL</p>
          </button>
          <button onClick={() => handleClick("%")}>
            <p>%</p>
          </button>
          <button onClick={() => handleClick("/")}>
            <p>÷</p>
          </button>
        </div>
        <div className="row-2">
          <button onClick={() => handleClick("7")}>
            <p>7</p>
          </button>
          <button onClick={() => handleClick("8")}>
            <p>8</p>
          </button>
          <button onClick={() => handleClick("9")}>
            <p>9</p>
          </button>
          <button onClick={() => handleClick("*")}>
            <p>X</p>
          </button>
        </div>
        <div className="row-3">
          <button onClick={() => handleClick("4")}>
            <p>4</p>
          </button>
          <button onClick={() => handleClick("5")}>
            <p>5</p>
          </button>
          <button onClick={() => handleClick("6")}>
            <p>6</p>
          </button>
          <button onClick={() => handleClick("-")}>
            <p>-</p>
          </button>
        </div>
        <div className="row-4">
          <button onClick={() => handleClick("1")}>
            <p>1</p>
          </button>
          <button onClick={() => handleClick("2")}>
            <p>2</p>
          </button>
          <button onClick={() => handleClick("3")}>
            <p>3</p>
          </button>
          <button onClick={() => handleClick("+")}>
            <p>+</p>
          </button>
        </div>
        <div className="row-5">
          <button id="zero-button" onClick={() => handleClick("0")}>
            <p>0</p>
          </button>
          <button onClick={() => handleClick(".")}>
            <p>.</p>
          </button>
          <button onClick={() => handleClick("=")}>
            <p>=</p>
          </button>
        </div>
      </div>
    </div>
  );
};

export default Calculator;

應用程式元件

App 元件呈現計算器元件並為應用程式添加頁首和頁尾。

import Calculator from "./components/Calculator";
import "./App.css";
const App = () => {
  return (
    <div className="app">
      <div className="header">
        <h1>Calculator</h1>
      </div>
      <Calculator />
      <div className="footer">
        <p>Made with ❤️ by Coding4Dev</p>
      </div>
    </div>
  );
};

export default App;

CSS 樣式

CSS 樣式確保計算器位於螢幕中央並具有現代外觀。按鈕的風格簡潔且響應靈敏。

* {
  box-sizing: border-box;
}
body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
}
.app {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.header {
  margin: 20px;
}

.calculator {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 350px;
  height: 450px;
  color: white;
  background-color: black;
  border-radius: 15px;
  box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
}
.output-box {
  width: 300px;
  height: 100px;
  color: rgb(53, 52, 52);
  background-color: rgb(216, 216, 216);
  border-radius: 12px;
}
.output-box h1 {
  margin-left: 15px;
  font-size: 25px;
  overflow: hidden;
}
.output-box h2 {
  margin-left: 15px;
  font-size: 25px;
}
.buttons {
  margin-top: 15px;
  width: 350px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.buttons p {
  font-size: 14px;
  font-weight: 600;
  color: white;
}
button {
  width: 72px;
  margin: 4px;
  border-radius: 12px;
  border: none;
  background-color: #536493;
}
button:hover {
  background-color: #374262;
}
#zero-button {
  width: 150px;
}
.footer {
  margin: 20px;
}

安裝與使用

要開始此項目,請複製儲存庫並安裝相依性:

git clone https://github.com/abhishekgurjar-in/Calculator.git
cd calculator-react
npm install
npm start

這將啟動開發伺服器並在預設網頁瀏覽器中開啟計算器。

現場演示

您可以在此處查看計算器的現場演示。

結論

這個簡單的計算器專案是練習 React 技能並了解如何在 React 應用程式中管理狀態和處理使用者輸入的絕佳方法。請隨意透過添加更多高級功能(例如科學計算器模式)或整合其他功能來擴展此項目。

製作人員

  • 靈感:這個專案的靈感來自於線上提供的各種簡單計算器。

作者

Abhishek Gurjar 是一位充滿熱情的 Web 開發人員,專注於建立直覺且響應靈敏的 Web 應用程式。跟隨他的旅程並在 GitHub 上探索更多專案。

以上是用 React 建立一個簡單的計算器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn