如何使用状态/属性在图像阵列中循环显示?

时间:2019-06-27 15:26:52

标签: javascript reactjs react-native

我有一个react-native应用程序,我想使用包含图像的状态/属性传递对象数组。我想在按下按钮时循环显示图像。我已经为此工作了一段时间,无法弄清楚。有人介意看看吗?我是本机反应的新手,所以如果您认为我应该以不同的方式进行操作,请告诉我。谢谢!!

我已经浏览javascript / react-native已有一段时间了,无法弄清楚该怎么做。

using (StreamReader streamReader = new StreamReader(Client.GetStreamAsync("https://" + User + ".cloudant.com/" + Database + "/_all_docs").Result))
{
    JObject responseContent = (JObject)JToken.ReadFrom(new JsonTextReader(streamReader));
    System.Collections.Generic.KeyValuePair<string, Newtonsoft.Json.Linq.JToken> ids = new KeyValuePair<string, JToken>("", null);
    JToken docsArray = responseContent.GetValue("rows");// type Newtonsoft.Json.Linq.JToken {Newtonsoft.Json.Linq.JArray}

    List<string> IDS = new List<string>();
    foreach (JToken doc in docsArray)
    {
        //Console.WriteLine(doc.ToString());
        string id = doc["id"].Value<string>();
        IDS.Add(id);
    }
    return IDS;
}

我只是希望能够在按下按钮时循环显示图像,并以某种方式能够访问我正在使用的内容。

1 个答案:

答案 0 :(得分:1)

将当前图像索引保持在某种状态,并在按下按钮时增加ir。

import React, { useState } from 'react'

export default function App() {
  const [currentImageIndex, setCurrentImageIndex] = useState(0)

  return (
    <View>
      <View>
        {
            imageholder2[currentImageIndex] &&
              <Image
                key={imageholder2[currentImageIndex].id}
                style = {{
                  width: 300,
                  height: 300,
                }}
                source={imageholder2[currentImageIndex].actualimage} 
              />
        }
      </View>
      <View>
      <Button 
          title= "Press me" 
          onPress={() => setCurrentImageIndex(currentImageIndex == imageholder2.length - 1 ? 
              0 : 
              currentImageIndex + 1
          )}
      />
      </View>
    </View>
  );
}

此外,最好将图像保持在一个状态。

很抱歉没有给出打字稿答案。

相关问题