iT邦幫忙

2025 iThome 鐵人賽

DAY 30
0

專案目標

今天是最後一天了!
前面學了JavaScript許多東西,所以就來把之前學過的東西做成專案吧!

今天我們來製作一個可以查詢即時天氣的小App!

功能

  • 使用者輸入城市名稱後,按下查詢按鈕
  • App 會連線到 OpenWeatherMap API 取得該地的即時天氣
  • 顯示天氣描述、溫度、濕度等資訊
  • 若輸入錯誤或找不到城市,顯示提示訊息
  1. 建立專案
    使用 Create React App:

    npx create-react-app weather-app
    cd weather-app
    npm start
    
  2. 申請免費 API Key
    OpenWeatherMap 註冊帳號後,取得一組免費的API key

我們要用三個主要部分來組成這個App:

  1. 輸入框與按鈕 — 讓使用者輸入城市名稱
  2. 天氣資訊區塊 — 顯示查詢結果
  3. 非同步資料請求 — 使用 Fetch 取得 API 資料
import React, { useState } from "react";

function WeatherApp() {
  const [city, setCity] = useState("");
  const [weather, setWeather] = useState(null);
  const [error, setError] = useState("");

  const API_KEY = "API_KEY"; //換成自己的

  const getWeather = async () => {
    if (!city) return;

    try {
      setError("");
      const response = await fetch(
        `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric&lang=zh_tw`
      );

      if (!response.ok) {
        throw new Error("找不到這個城市,請再試一次!");
      }

      const data = await response.json();
      setWeather(data);
    } catch (err) {
      setWeather(null);
      setError(err.message);
    }
  };

  return (
    <div className="flex flex-col items-center p-6 bg-blue-100 min-h-screen">
      <h1 className="text-2xl font-bold mb-4">天氣查詢小工具</h1>

      <div className="flex gap-2 mb-4">
        <input
          type="text"
          placeholder="輸入城市名稱..."
          value={city}
          onChange={(e) => setCity(e.target.value)}
          className="border p-2 rounded"
        />
        <button
          onClick={getWeather}
          className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
        >
          查詢
        </button>
      </div>

      {error && <p className="text-red-600">{error}</p>}

      {weather && (
        <div className="bg-white p-4 rounded shadow-md w-64 text-center">
          <h2 className="text-xl font-semibold mb-2">{weather.name}</h2>
          <p>{weather.weather[0].description}</p>
          <p>溫度:{weather.main.temp} °C</p>
          <p>濕度:{weather.main.humidity}%</p>
        </div>
      )}
    </div>
  );
}

export default WeatherApp;

上一篇
Day29:React之初探
系列文
30天入門Java Script30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言