2017-09-04 93 views
0

我正在嘗試使用TouchableOpacity.onPress處理ListView中的一排物品的水龍頭,但我嘗試的所有內容都以一種稍微不同的方式失敗。我有renderRow函數,提供給ListView.renderRow。在這裏我想做的事:如何使用`TouchableOpacity`中的數據獲得'onPress`回調

renderRow(rowData) { 
    return (
    <TouchableOpacity onPress= {() => this.tapRow(rowData) }> 
     <View style={{margin: 5, backgroundColor: "#EEE" }}> 
      <Text>{rowData.text}</Text> 
     </View> 
    </TouchableOpacity> 
) 
} 

而且我tapRow功能是:

tapRow(rowData) { 
    console.log("Tapped Row: " + rowData.id) 
} 

這將導致錯誤_this3.tapRow is not a function ... _this3.tapRow is undefined

查看參考資料我也嘗試將this.tapRow = this.tapRow.bind(this)添加到構造函數中,但這沒有幫助。

對於測試我也做了onPress={this.tapRow}。這不會導致錯誤,但函數永遠不會被調用(我做一個簡單的console.log來驗證)

如何獲得在onPress中調用的函數併爲其提供參數?

+0

嘗試這樣做就tapRow,tapRow =(rowData)=> { 的console.log( 「TEST」); } –

+0

@GaneshCauda這是我試過的東西,現在再試一次。同樣的問題'_this3.tapRow'未定義。 –

+0

ah和onpress,試着做這件事,onPress = {()=> this.tapRow({rowData})} –

回答

0

綁定構造的renderRow功能:

constructor (props) { 
    super(props) 
    this.renderRow = this.renderRow.bind(this) 
} 
相關問題