1. 程式人生 > >React Native ListView的Item設定點選事件時null is not an object

React Native ListView的Item設定點選事件時null is not an object

先貼下程式碼:

<ListView 
                    contentContainerStyle = {styles.list}
                    pageSize={2}
                    dataSource = {this.state.dataSource}
                    renderRow={this._renderRow}
                />

_renderRow(rowData) {
        console.log('rowData.url: '+ rowData.url) ;
        console.log('rowData.name: '+ rowData.name) ;
        return (
            <TouchableOpacity
onPress = {() =>
this._pressRow(rowData.url)} underlayColor = "transparent" > <View> <View style={styles.row}> <Text style={styles.text}> {rowData.name} </Text> </View> </View> </TouchableOpacity
>
) }

ListView裡的renderRow={this._renderRow},然後會報錯,顯示null is not an object (evaluating '_this3._pressRow'),上圖:
這裡寫圖片描述
一看就知道是找不到方法,後來查閱這個資料,知道了解決方法,原來renderRow要與外面的this繫結起來,這個跟Android裡的上下文環境Context很像:

<ListView 
                    contentContainerStyle = {styles.list}
                    pageSize={2}
dataSource = {this.state.dataSource} renderRow={this._renderRow.bind(this)} />