React-Native无法读取未定义的属性“bind”

时间:2017-10-16 09:07:08

标签: reactjs react-native native

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

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

SomeOne可以帮助我吗?谢谢!

1 个答案:

答案 0 :(得分:5)

这是因为你忘了用映射回调函数绑定this,回调函数里面的this不是指反应类上下文,在这里:

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

使用arrow function

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

现在用第一种或第二种方法写身体,两者都可以。

相关问题