简体   繁体   English

从动态生成的列表中动态选择元素

[英]Dynamically Select Element from Dynamically Generated List

I am trying to select an element from a dynamically generated list of elements at the event of a touch.我试图在触摸事件时从动态生成的元素列表中选择一个元素。 I am generating the list with a for loop.我正在使用 for 循环生成列表。 In each element I add an event listener and push the navigation stack to another screen.在每个元素中,我添加了一个事件侦听器并将导航堆栈推送到另一个屏幕。 This works perfectly fine.这工作得很好。 At the same time however, I try to update the state to the selected element.然而,与此同时,我尝试将状态更新为所选元素。 Because I only want to update the state once the user presses the view/button, I am calling the function inside the event listener.因为我只想在用户按下视图/按钮后更新状态,所以我在事件侦听器中调用该函数。 The issue is, that the state is always updated to the last index of the for loop and I am not able to access the index of each element.问题是,状态总是更新到 for 循环的最后一个索引,我无法访问每个元素的索引。 Can anybody help me with this?有人可以帮我解决这个问题吗?

const ListRecommendations = [];
for (var i = 0; i < this.Data.length; i++) {
  ListRecommendations.push(
    <View key={i}
      style={styles.Recommendation}

      onStartShouldSetResponder={() => {
        Navigation.push(this.props.componentId, {
          component: {
            name: 'secondScreen',
          }
        });
        this.setState(i);
      }}
      
    >
      <ImageBackground 
        source= {{uri: this.Data[i].FilePath}}
        style={styles.backgroundImage}
      >
        <Text style={styles.Title}>{this.Data[i].Title}</Text>
      </ImageBackground>
    </View>
  )
}

you use a var in you loop but you should know that var declaration doesn't work on for block scope, and i will be equal the last value您在循环中使用var ,但您应该知道var声明不适用于块作用域,并且i将等于最后一个值

to fix it use let修复它使用let

for(let  I=0; I < 10; I++){
  // ...
}

Please read more https://javascript.info/variables请阅读更多https://javascript.info/variables

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

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