You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native天气应用:如何将OpenWeather API数据传递给组件?

React Native 天气应用:解决数据传递到Title组件的问题

问题分析

你当前的代码存在几个导致数据无法正常传递/渲染的问题:

  • JSX中直接使用console.log语法错误:在JSX元素内部不能直接写console.log,这会被视为无效的JSX节点。
  • Title组件未接收完整的props:你传递了temperature和description,但Title组件只解构了name参数,无法获取另外两个值。
  • 未定义的样式引用:Title组件中使用的FontStyle没有通过StyleSheet.create定义,会导致样式失效。

修复后的代码

1. 修正WeatherData.js

把console.log移到JSX之外,确保语法合规:

import React from 'react';
import { View, Text } from 'react-native';
import Title from './Title'; // 确保正确导入Title组件

const Data = ({ weatherData }) => {
  // 在组件逻辑中打印数据,而非JSX节点内
  console.log('Weather Data:', weatherData);

  return (
    <View>
      {weatherData ? (
        <View>
          <Title
            name={weatherData?.name}
            temperature={weatherData?.main?.temp}
            description={weatherData?.weather[0]?.description}
          />
        </View>
      ) : (
        <Text>No weather data available</Text>
      )}
    </View>
  );
};

export default Data;

2. 修正Title.tsx

接收所有传递的props,并正确定义样式:

import { Text, View, StyleSheet } from "react-native";

const Title = ({ name, temperature, description }) => {
  // 转换OpenWeather默认的开尔文温度为摄氏度
  const formattedTemp = temperature ? `${Math.round(temperature - 273.15)}°C` : '';
  // 格式化天气描述,首字母大写
  const formattedDesc = description ? description.charAt(0).toUpperCase() + description.slice(1) : '';

  return (
    <View style={styles.container}>
      <Text style={styles.cityName}>{name}</Text>
      <Text style={styles.dateText}>Tue, Jun 30</Text>
      {/* 渲染传递的气温和天气描述 */}
      {formattedTemp && <Text style={styles.tempText}>{formattedTemp}</Text>}
      {formattedDesc && <Text style={styles.descText}>{formattedDesc}</Text>}
    </View>
  );
};

// 用StyleSheet定义组件样式
const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
  },
  cityName: {
    fontWeight: 'bold',
    fontSize: 24,
  },
  dateText: {
    fontSize: 16,
    color: '#666',
  },
  tempText: {
    fontSize: 36,
    fontWeight: 'bold',
    marginTop: 8,
  },
  descText: {
    fontSize: 18,
    color: '#444',
    marginTop: 4,
  },
});

export default Title;

额外注意事项

  • 确认OpenWeather API返回的数据结构正确,weatherData确实包含name、main.temp、weather[0].description字段。
  • 组件导入路径要匹配实际文件位置,避免因路径错误导致组件无法加载。
  • 若需要处理加载状态,可在weatherData未就绪时添加加载指示器。

内容的提问来源于stack exchange,提问作者Saif Sabry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 20:10:09