简体   繁体   English

映射时有条件地显示 svg 个图标(React js 应用程序)

[英]display svg icons conditionally when mapping (React js app)

I'm building a simple app using the Open Weather API. The API call works (I have in my App root component) and returns a list array with 8 objects that contain the forecast (divided into 3-hr chunks).我正在使用 Open Weather API 构建一个简单的应用程序。API 调用有效(我在我的应用程序根组件中有)并返回一个列表数组,其中包含 8 个包含预测的对象(分为 3 小时块)。 I have a folder with SVG images that I need to show depending on the id provided by each object. That worked in my Current Weather component.我有一个包含 SVG 图像的文件夹,我需要根据每个 object 提供的 ID 显示这些图像。这在我的当前天气组件中有效。 I stored a switch statement in a function and I pulled the information just from the list[0].我在 function 中存储了一个 switch 语句,然后我从列表 [0] 中提取了信息。 I'm trying to use the same function (passing it as props from CW) in the Future Weather component, in which I'm mapping to get the forecast for the next 24 hr.我正在尝试在 Future Weather 组件中使用相同的 function(将其作为 CW 的道具传递),我在其中映射以获得接下来 24 小时的预报。 The map works (I'm getting temperature, time and icon code) but I don't know how to use that function to display the icons for the FW component (both CW and FT are stateless). map 有效(我正在获取温度、时间和图标代码)但我不知道如何使用 function 来显示 FW 组件的图标(CW 和 FT 都是无状态的)。 I'm trying to reuse that function and not repeat myself.我正在尝试重用 function 而不是重复自己。 Thanks!谢谢!

Current Weather component当前天气组件

const CurrentWeather = (props) => {
  let weatherInfo = props.weatherData.list;

  if (!weatherInfo) {
    return 'No info to display';
  }

  let id = props.weatherData.list[0].weather[0].id;

  function renderSwitch() {
    switch (true) {
      case id < 300:
        id = <img className="forecast-img" src={storm} alt="storm icon" />;
        break;
      case id >= 300 && id < 500:
        id = <img className="forecast-img" src={drizzle} alt="drizzle icon" />;
        break;
      case id >= 500 && id < 600:
        id = <img className="forecast-img" src={rain} alt="rain icon" />;
        break;
      case id >= 600 && id < 700:
        id = <img className="forecast-img" src={snow} alt="snow icon" />;
        break;
      case id >= 700 && id < 800:
        id = <img className="forecast-img" src={fog} alt="fog icon" />;
        break;
      case id === 800:
        id = <img className="forecast-img" src={clear} alt="clear icon" />;
        break;
      case id === 801:
        id = <img className="forecast-img" src={pcloudy} alt="particularly cloudy icon" />;
        break;
      case id > 800 && id < 806:
        id = <img className="forecast-img" src={mcloudy} alt="mostly cloudy icon" />;
        break;
      default:
        id = 'missing id';
    }
    return id;
  }

  return (
    <section className="general-forecast">
      <div className="forecast-caption">
        {/* {props.weatherIcon} */}
        {renderSwitch()}
        <p>{weatherInfo[0].weather[0].description}</p>
        <div className="temperature">
          <p>
            <strong>Temperature </strong>
            {Math.floor(weatherInfo[0].main.temp_min)}&#8451; to{' '}
            {Math.ceil(weatherInfo[0].main.temp_max)}
            &#8451;
          </p>
        </div>
        <div className="percentages">
          <ul>
            <li>
              <strong>Humidity </strong>
            </li>
            <li>{weatherInfo[0].main.humidity}%</li>
            <li>
              <strong>Pressure </strong>
            </li>
            <li>{weatherInfo[0].main.pressure}</li>
          </ul>
        </div>
      </div>
      <FutureWeather weatherData={weatherInfo} weatherIcon={renderSwitch} />
    </section>
  );
};

export default CurrentWeather;

Future Weather component未来天气组件

const FutureWeather = (props) => {
  let weatherInfo = props.weatherData;
  // let weatherIcon = props.weatherIcon;

  if (!weatherInfo) {
    return 'No info to display';
  }

  const weatherData = weatherInfo.map((element) => {
    return (
      <div className="next-forecast" key={element.dt}>
        <li>{element.dt_txt.slice(-8, -3)}</li>
        <li>{element.weather[0].id}</li>
        <li>{Math.round(element.main.temp)}&#8451;</li>
      </div>
    );
  });

  return (
    <div>
      <section className="detailed-forecast">
        <p>Future Weather Here</p>
        <ul className="detailed-forecast">{weatherData}</ul>
      </section>
    </div>
  );
};

export default FutureWeather;

Currently, you're giving the renderSwitch function as a property weatherIcon to the FutureWeather component.目前,您将renderSwitch function 作为属性weatherIcon提供给FutureWeather组件。 So, if you want to use it, you can call weatherIcon() (with parentheses) inside of FutureWeather .所以,如果你想使用它,你可以在FutureWeather中调用weatherIcon() (带括号)。

It would also be possible to give the result of renderSwitch() as the property by calling the function like this:也可以通过像这样调用 function 来将renderSwitch()结果作为属性提供:

<FutureWeather weatherData={weatherInfo} weatherIcon={renderSwitch()} />

In this case, you would insert { weatherIcon } in the template of FutureWeather .在这种情况下,您将在FutureWeather的模板中插入{ weatherIcon }

In both cases, you should know that you only use one single icon for all kinds of usages, because you calculate the id only once (not for each day).在这两种情况下,您应该知道您只使用一个图标用于各种用途,因为您只计算一次id (不是每天)。

Generally, I would recommend not to use a global variable, but use the id as a parameter for the function call.一般来说,我会建议不要使用全局变量,而是使用id作为 function 调用的参数。 It will be much easier to test the function, if it doesn't have side effects.如果没有副作用,测试 function 会容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM