首页 > 解决方案 > 我怎样才能让按钮写文字?

问题描述

我正在开发一个简单的天气应用程序,并且我想要一个按钮,当单击该按钮时,它将显示来自 API 的数据。我知道如何获取 API 数据,以及如何创建按钮。我不知道的是如何让点击时反应在网页上写下文字。

这是我的天气组件:

import React, { Component } from "react";
import axios from "axios";
import Button from "react-bootstrap/Button";
import Loader from "react-loader-spinner";
import HumanDate from "./HumanDate";
import WeatherIcon from "./WeatherIcon";
import "./Weather.css";

export default class Weather extends Component {
  apiKey = "<MY-KEY>";
  apiRoot = "https://api.openweathermap.org";

  state = {
    loaded: false
  };

  showResults = response => {
    this.setState({
      weatherLoaded: true,
      weather: {
        date: response.data.dt,
        timezone: response.data.timezone,
        city: response.data.name,
        description: response.data.weather[0].description,
        icon: response.data.weather[0].icon,
        temperature: Math.round(response.data.main.temp),
        humidity: response.data.main.humidity,
        wind: Math.round(response.data.wind.speed)
      }
    });
  };

  componentDidMount() {
    let apiUrl = `${this.apiRoot}/data/2.5/weather?q=${this.props.city}&appid=${
      this.apiKey
    }&units=metric`;
    axios.get(apiUrl).then(this.showResults);
  }
  render() {
    if (this.state.weatherLoaded) {
      return (
        <div>
          <Button variant="outline-secondary" onClick={this.getCurrentTemp}>
            Current Weather
          </Button>
          <br />
          <br />
          <h1>{this.props.city}</h1>
          <ul>
            <li>
              <HumanDate
                timestamp={this.state.weather.date}
                timezone={this.state.weather.timezone}
              />
            </li>
            <li className="description">{this.state.weather.description}</li>
          </ul>
          <div className="row">
            <div className="col-sm-6">
              <div className="clearfix">
                <div className="weather float-left">
                  <WeatherIcon weather={this.state.weather.description} />
                </div>
                <div className="temperature float-left">
                  {this.state.weather.temperature}
                  <small>°C</small>
                </div>
              </div>
            </div>
            <div className="col-sm-6">
              <ul>
                <li>Humidity: {this.state.weather.humidity}%</li>
                <li>Wind: {this.state.weather.wind}km/h</li>
              </ul>
            </div>
          </div>
        </div>
      );
    } else {
      return (
        <div className="loader">
          <Loader type="Plane" color="#333" height="100" width="100" />;
        </div>
      );
    }
  }
}


这就是我在考虑当前位置的情况下获取数据的方式:

  getCurrentTemp() {
    function showTemp(response) {
      this.setState({
        weatherLoaded: true,
        weather: {
          date: response.data.dt,
          timezone: response.data.timezone,
          city: response.data.name,
          description: response.data.weather[0].description,
          icon: response.data.weather[0].icon,
          temperature: Math.round(response.data.main.temp),
          humidity: response.data.main.humidity,
          wind: Math.round(response.data.wind.speed)
        }
      });
    }

    function showPosition(position) {
      let latitude = position.coords.latitude;
      let longitude = position.coords.longitude;

      let apiKey = "<MY-KEY>";
      let apiEndPoint = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${apiKey}&units=metric`;
      axios.get(apiEndPoint).then(showTemp);
    }
    navigator.geolocation.getCurrentPosition(showPosition);
  }

  render() {
    return <button onClick={this.getCurrentTemp}>Current Weather</button>;
  }

所以想法是让函数“getCurrentTemp”编写html而不是警报信息。

谢谢!

标签: reactjs

解决方案


这个想法是,在从 api 接收数据后,您可以将该数据设置为组件状态中的变量。然后你可以在 render 方法中使用this.state.whateverYouCalledIt.

例如:<div>{this.state.weather.temperature}</div>

确保仅weather.temperature在天气不为空时阅读。您可以使用它this.state.weather && this.state.weather.temperature来实现这一点。

最后,您可以使用 javascript 模板文字来显示变量以及您想要的格式,例如:

render() {
    return <div>{`Current Weather: ${this.state.weather && this.state.weather.temperature}`}</div>;
}

推荐阅读