【问题标题】:React Native loop thisReact Native 循环这个
【发布时间】:2016-04-23 23:36:40
【问题描述】:

当我将onPress 放入地图循环时,它不起作用。如何解决?

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

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    this 指的是错误的上下文,您需要对范围进行词法绑定,这就是胖箭头函数将为您做的事情。

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

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

    此外,您需要将 map 函数绑定到正确的上下文,如下所示:

    <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>
    

    我建立了一个工作项目here

    https://rnplay.org/apps/_PmG6Q

    【讨论】:

    • 感谢您的回答,但收到错误undefined' is not an object (evaluating '_this._handlePress') :(
    猜你喜欢
    • 2017-07-07
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2019-09-13
    • 1970-01-01
    • 2022-09-30
    相关资源
    最近更新 更多