【问题标题】:Concatenate Variable with JSON in JSX / React Native在 JSX / React Native 中使用 JSON 连接变量
【发布时间】:2020-02-19 21:48:00
【问题描述】:

因此,我正在构建其中一款天气应用程序,其中包含基于天气状况的自定义报价。下面的代码有效......但如您所见,我有多个引号。我生成了一个随机数变量,它也有效。我正在尝试将该变量添加到weatherCases JSX...我知道可以做到,但是伙计,我无法弄清楚使其工作的语法...

报价工作

const weatherCases = {

   "clear sky": {
      title: "clear sky",
      quote1: "Custom quote 1.",
      quote2: "Custome quote 2",
      quote3: "Custom quote 3",
      ...
  }
}

function Forecast({ temp, weatherName, city }) {
  return ( 
    <View style={styles.forecastContainer}> 

      <View style={styles.forecastTopContainer}>
        <View>
          <Text style={styles.quoteText} >{weatherCases[weatherName].quote}</Text>
        </View>
      </View>
    </View>
  );
}

我正在尝试获取随机引用(这是使该行正常工作的十几个编辑之一:

function Forecast({ temp, weatherName, city }) {

  const randomNumber = (Math.floor(Math.random() * 30));
  console.log(randomNumber);
  //console.log(weatherName);
  return ( 
    <View style={styles.forecastContainer}> 

      <View style={styles.forecastTopContainer}>
        <View>
          <Text style={styles.quoteText} >{weatherCases[weatherName].quote.{randomNumber}}</Text>
        </View>
      </View>
    </View>
  );
}

【问题讨论】:

    标签: json react-native jsx


    【解决方案1】:

    我相信你正在努力做到这样

    weatherCases[weatherName]["quote" + randomNumber.toString()]

    例如结果 randomNumber 是 3 它会是这样的

    weatherCases["clear sky"]["quote3"]
    

    【讨论】:

    • 哦,天哪。我是如此接近!谢谢,谢谢@NaldPrabha
    • 很高兴它对@EricMessick 有所帮助,如果您认为它可以解决您的问题,请将其标记为正确答案,以便其他人可以将其作为解决相同问题的参考
    猜你喜欢
    • 2015-07-10
    • 2020-02-23
    • 2021-09-06
    • 2020-10-08
    • 2018-05-10
    • 1970-01-01
    • 2021-11-28
    • 2019-10-09
    • 1970-01-01
    相关资源
    最近更新 更多