在 React Native 中点击事件后渲染动态组件

Rendering dynamic component after on click event in react native

我在 React Native 的地图上有一组标记。

在那个标记上的点击事件发生时,我想显示一个我有 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>)
    }

您可以使用 let 声明您的 i 变量,使其作用域限于封闭块。

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>
  );
}