通过构建一个简单的天气应用来学习 React
不知道如何学习 React?那就开始构建这个应用吧!
当你开始学习一项技术时,要从构建小型项目开始,这样你才能获得该技术的概念和事实知识。
React 是一个新兴的前端框架,可以方便地构建 Web 应用程序。它有助于构建单页应用程序,这些应用程序可以直接在浏览器中运行,无需在使用过程中重新加载页面。
应用功能
- 显示设备所在位置的温度、地区、风速、气压、降水量和湿度。
- 在搜索栏中,根据用户指定的位置显示上述天气信息。
让我们开始吧
请确保您的系统中已安装 React、Node.js 和 NPM。
要在创建项目时,请在终端中运行以下命令:
npx create-react-app weather_app
cd weather_app
npm start
现在我们将看到这个屏幕,可以在这里查看本地服务器上应用程序的实时更新。
之后,您将获得项目所需的软件包。我们无需担心这些软件包,因为我们主要关注的是“App.js”。“App.js”是该文件中的主要组件,它充当其他组件的容器。
我们需要从“App.js”中移除默认内容。
创建类
创建一个类组件,并引入`extendsReact.Component`。这将继承 React 组件,并允许该组件访问 `React.component` 的函数。该组件还需要一个 `render` 方法来返回 HTML。
现在,我们将设置状态并将输入分配给状态对象。
State 是 React 组件类的一个对象,可以在其生命周期内进行修改,但不能从外部访问。
class App extends React.Component {
state= {
coords:{
latitude:28,
longitude:77
},
}
render() {
return (
<div className="App">
<div className="container">
</div>
</div>
);
}
}
注意:如果设备定位功能失效,我们将在此处为纬度和经度分配默认值。
获取当前位置的天气信息
我们将使用componentDidMount()方法来设置设备的纬度和经度。该方法是生命周期方法之一,会在组件挂载后立即调用。
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
let newCoords={
latitude:position.coords.latitude,
longitude:position.coords.longitude
}
this.setState({coords:newCoords});
获取当前位置,并将其纬度和经度设置到状态对象中。
接下来,我们将使用 REST API 来获取应用程序所需的天气详情。
获取 API 密钥
要获取 API 密钥,您需要在此处登录,或者您可以使用任何其他外部 API。
我们将使用 Axios,这是一个用于向 REST API 发送请求的 JavaScript 库。因此,请在终端中使用 ` npm install axios` 命令安装它,然后在类组件中导入它。
现在,我们将使用 get() 方法调用 API,并传递状态对象中设置的纬度和经度值。之后,我们将检索天气数据并将其设置到状态中的一个新对象中。
Axios.get(`http://api.weatherstack.com/current?access_key=your_API _key=
${this.state.coords.latitude},${this.state.coords.longitude}`).then(res => {
let Weather_data = {
temperature: res.data.current.temperature,
description: res.data.current.weather_descriptions[0],
location: res.data.location.name,
region: res.data.location.region,
country: res.data.location.country,
wind_speed: res.data.current.wind_speed,
pressure: res.data.current.pressure,
precip: res.data.current.precip,
humidity: res.data.current.humidity,
img: res.data.current.weather_icons
}
this.setState({data:Weather_data})
})
显示天气数据
从 API 获取数据后,我们需要将其显示出来,因此我们将创建一个用于显示数据的组件。创建组件后,您可以根据需要添加应用程序的动态结构(HTML)和样式。
在这个组件中,我们将访问“App.js”中的数据,因此需要使用 props 来获取数据。Props 是 React 中的一个特殊关键字,它表示可以从父组件单向传递数据的属性。
App.js
render() {
return (
<div className="App">
<div className="container">
<Navbar changeRegion={this.changeRegion} changeLocation={this.changeLocation}/>
<Display Weather_data={this.state.data}/>
</div>
</div>
);
}
Display.js
import React from 'react'
export default function Display(props) {
const { temperature, description, location, region, country, wind_speed, pressure, precip, humidity, img } = props.Weather_data;
return (
<div className="weather-wrapper">
<div className="weather-card">
<div className="header">
<img className="mainImg" src={img} alt="weather-img" />
<h1>{temperature}<sup>o</sup>C , {description}</h1>
<h4>{location}</h4>
<p>{region} , {country}</p>
</div>
<p><b>Wind Speed</b>(km/hr)</p>
<h3>{wind_speed}</h3>
<p><b>Preassure</b>(millibar)</p>
<h3>{pressure}</h3>
<p><b>Precipitation</b>(mm)</p>
<h3>{precip}</h3>
<p><b>Humidity</b>(%)</p>
<h3>{humidity}</h3>
</div>
</div>
)
}
现在屏幕上将显示天气信息。之后,我们将采用类似的方法显示所搜索位置的天气信息。
显示搜索位置的天气信息
当用户在搜索框中指定位置时,系统会使用 Navbar 组件将搜索到的位置值赋给状态对象。现在,我们可以将包含搜索到的位置信息的状态对象传递给 API 以获取天气信息。最后,系统会使用 Display 组件显示这些天气信息。
Navbar.js
import React from 'react';
import { FaSistrix } from "react-icons/fa";
export default function Navbar(props) {
return (
<div className="row">
<div className="col-md-6">
<h1 className="title">Weather App</h1>
<div className="col-md-6">
<form action="" autocomplete="on" className="region" onSubmit={(e) => { props.changeLocation(e) }}>
<input type="text" className="regioninput" placeholder="Select your region" onChange={(p) => { props.changeRegion(p.target.value) }} />
<button type="submit" class="searchbutton"><FaSistrix/></button>
</form>
</div>
</div>
</div>
)
}
App.js
changeLocation = (e) => {
e.preventDefault();
if(this.state.regionInput){
Axios.get(`http://api.weatherstack.com/current?access_key=your_acess_key&query=${this.state.regionInput}`).then(res => {
if(res.status===200 && res.data.request){
let Weather_data = {
temperature: res.data.current.temperature,
description: res.data.current.weather_descriptions[0],
location: res.data.location.name,
region: res.data.location.region,
country: res.data.location.country,
wind_speed: res.data.current.wind_speed,
pressure: res.data.current.pressure,
precip: res.data.current.precip,
humidity: res.data.current.humidity,
img: res.data.current.weather_icons
}
this.setState({ data: Weather_data });
}
我们的Web应用程序的输出结果。
太棒了!!!我们已经成功构建了这款应用。希望您已经理解了 React 的开发流程和概念。
这是该项目的GitHub源代码。
感谢您阅读本文。这是我的处女作,我尽力使文章通俗易懂、内容丰富。希望以后能写得更好。祝您编程愉快!
如果您遇到任何问题,也欢迎随时通过LinkedIn与我联系。
文章来源:https://dev.to/nikitha_janardhanan/learn-react-by-building-a-simple-weather-app-1c44

