React Native 循环这个 [英] React Native loop this

查看:64
本文介绍了React Native 循环这个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将 onPress 放在地图循环中时,它不起作用.怎么解决?

when I put onPress in a map loop, it doesn't work. how to fix it?

var PageOne = React.createClass({
  _handlePress() {
    this.props.navigator.push({id: 2,});
  },
  render () {
      return (
        <View>          
          <TouchableOpacity onPress={this._handlePress}> //work here 
          <Text> One </Text>
          </TouchableOpacity>
          <View style={styles.albums}>
          {
            list.map(function(item, index){
              return (
                <TouchableOpacity key={index} onPress={this._handlePress}> //doesn't work hehre
                  <Text>{item}</Text>
                </TouchableOpacity>
              )
            })
          }
            </View>
      </View>
      );
  }
});

推荐答案

this 指的是错误的上下文,你需要在词法上绑定作用域,这就是粗箭头函数会做的为你.

this is referring to the wrong context, you need the scope to be lexically bound, which is what the fat arrow function will do for you.

尝试像这样调用您的函数:

Try calling your function like this:

onPress={ () => this._handlePress() }

此外,您需要像这样将 map 函数绑定到正确的上下文:

Also, you need to bind the map function to the correct context like this:

<View style={styles.albums}>
  {
    list.map(function(item, index){
       return (
         <TouchableOpacity key={index} onPress={() => this._handlePress()}> 
           <Text>{item}</Text>
          </TouchableOpacity>
       )
     }.bind(this))
   }
</View>

或者像这样:

<View style={styles.albums}>
  {
    list.map((item, index) => {
       return (
         <TouchableOpacity key={index} onPress={() => this._handlePress()}> 
           <Text>{item}</Text>
         </TouchableOpacity>
       )
     })
   }
</View>

我在此处建立了一个工作项目.

I set up a working project here.

https://rnplay.org/apps/_PmG6Q

这篇关于React Native 循环这个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆