2017-10-16 111 views
1

兩個問題的特性「綁定」,如果我將函數像這樣綁定:陣營本地無法讀取未定義

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

有人能幫助我嗎?謝謝 !

回答

3

這是因爲你忘了綁定this地圖回調函數,this回調函數裏面是不是指反應類的上下文,這裏:

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

使用arrow function

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

現在用第一種或第二種方法寫身體,兩者都可以。

+0

你是我的國王謝謝;) –

+0

呵呵,很高興它解決了你的問題:) –