在React Native中点击事件后呈现动态组件

时间:2018-08-09 22:33:54

标签: reactjs react-native dynamic render

我在本机上的地图上有一组标记。

在该标记上发生点击事件时,我想显示一个具有其URL的动态图像。但是我一直处于不确定状态,因为循环中的i值始终取最后一个值。我该怎么做。

    show =(i) => {
          alert(JSON.stringify(i)) // always last value of i
    }  

    render(){
          var points = new Array();
          for(i=0 ; i<this.state.length ; i++) 
                 points[i]=(<MapView.Marker key={i} id ={i}
                 coordinate={{"latitude":this.state.resultlat[i],"longitude":this.state.resultlong[i]}}
                 title= {'You went to ' + this.state.names[i] }
                 onPress={()=>this.show(i)}
             <Image source={require('./a.jpg')} style={{width :30 , height:30}} />
           </MapView.Marker>)
    }

1 个答案:

答案 0 :(得分:1)

您可以使用i声明let变量,以使其范围限定在封闭块中。

var points = [];

for (let i = 0; i < this.state.length; i++) {
  points[i] = (
    <MapView.Marker
      key={i}
      id={i}
      coordinate={{
        latitude: this.state.resultlat[i],
        longitude: this.state.resultlong[i]
      }}
      title={"You went to " + this.state.names[i]}
      onPress={() => this.show(i)}
    >
      <Image source={require("./a.jpg")} style={{ width: 30, height: 30 }} />
    </MapView.Marker>
  );
}