TouchableHighLight onPress 在反应本机的地图函数内

TouchableHighLight onPress inside a map function in react native

我有一组图像要在 React Native 的组件中显示。
我使用 map 函数遍历数组并显示它。我在图片上方也有一个删除按钮。
相关代码是:

      this.state.imgs.map(function(img,i){
        return (
          <View style={{alignItems:'center',justifyContent:'center', height:75, width:75, borderRadius:25}}>
            <Image style={{position:'absolute',resizeMode:'cover', top:0,left:0, borderRadius:38,height:75, width:75, opacity:0.5}} source={{uri: img.path }} />
            <TouchableHighlight onPress={() => this.removeItem(i)}>
              <Image style={{}} source={require('./Images/images_asset65.png')} />
            </TouchableHighlight>
          </View>
          );
      })

问题是 TouchableHighlight,我有一个事件,当事件触发时我收到关于 "this" 的错误(未定义不是函数)。
我知道这是一个范围问题,但我无法弄明白。
这里使用箭头函数是否正确?

如果您想在 map 函数中使用 this,则必须更改为箭头函数,以便 this 指向外部范围。

  this.state.imgs.map((img, i) => {
    return (
      <View style={{alignItems:'center',justifyContent:'center', height:75, width:75, borderRadius:25}}>
        <Image style={{position:'absolute',resizeMode:'cover', top:0,left:0, borderRadius:38,height:75, width:75, opacity:0.5}} source={{uri: img.path }} />
        <TouchableHighlight onPress={() => this.removeItem(i)}>
          <Image style={{}} source={require('./Images/images_asset65.png')} />
        </TouchableHighlight>
      </View>
      );
  })

当您在代码中使用 function 关键字时,您将失去上下文,而 function 会创建自己的上下文。如果您使用 function,最好不要忘记将这些函数与 bind(this) 绑定,以便这些函数共享相同的上下文。因此,在您的相关代码中,您应该将最后一行更改为 }.bind(this))。最好记住在使用 function 关键字时以某种方式使用 bind(this),甚至更好的选择是不使用 function 并坚持使用 ES6 附带的好东西。最后但并非最不重要的一个应该总是阅读 docs.