【问题标题】:React-Native Cannot read property 'bind' of undefinedReact-Native 无法读取未定义的属性“绑定”
【发布时间】:2018-03-27 18:10:31
【问题描述】:

两个问题,如果我像这样绑定我的函数:

deleteTag = (id) => {
  console.log(id);
  id = 0;
  tabTag.splice(id, 1);
  --tabSize;
}

  componentTag() {
   return tabTag.map(function(item, id){
      return(
        <View key={id} style={styles.componentView}>
          <Icon name="ios-reorder"></Icon>
          <Text>{item.name}</Text> 
          <Slider style={styles.sliderBar} maximumValue={3} step={1} />
          <TouchableHighlight onPress={() => this.deleteTag.bind(this)}>
            <Icon name="close-circle"/>
          </TouchableHighlight>
        </View>
      );
    });
  }

我的错误是'无法读取未定义的属性'绑定'

否则

如果我在构造函数中绑定我的函数,什么都不会发生

 constructor(props) {
     this.deleteTag = this.deleteTag.bind(this);
  }

deleteTag = (id) => {
  console.log(id);
  id = 0;
  tabTag.splice(id, 1);
  --tabSize;
}

  componentTag() {
   return tabTag.map(function(item, id){
      return(
        <View key={id} style={styles.componentView}>
          <Icon name="ios-reorder"></Icon>
          <Text>{item.name}</Text> 
          <Slider style={styles.sliderBar} maximumValue={3} step={1} />
          <TouchableHighlight onPress={this.deleteTag}>
            <Icon name="close-circle"/>
          </TouchableHighlight>
        </View>
      );
    });
  }

有人可以帮助我吗?谢谢!

【问题讨论】:

    标签: reactjs react-native native


    【解决方案1】:

    这是因为你忘了绑定this和map回调函数,而回调函数里面的this不是指react类上下文,这里:

    tabTag.map(function(item, id){ .... })

    使用arrow function:

    tabTag.map((item, id) => { .... })
    

    现在用第一种或第二种方法编写正文,两者都可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-27
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多