2016-11-08 21 views
1

我有一羣用戶在<ListView/>中被渲染成<StatusSphere/>組件。如何使用onPress來定位節點而不是節點編號

當我點擊每個<StatusSpheres/>我想他們的個人uid的打印到控制檯(所以我可以進一步操縱它們)。

這是我遇到麻煩的地方;在反應我會使用e.target.value,甚至可以使用getAttributes。但在這裏我回來的是一個數字(例如237或248 ..等),我相信是節點號碼?

我發現,說,你可以使用另一種來源:

var ReactNativeComponentTree =require('react/lib/ReactNativeComponentTree'); ReactNativeComponentTree.getInstanceFromNode(nativeTag);

但沒有工作對我來說,似乎不可思議呢。

如何輕鬆訪問已存儲在實際組件上的uid?必須有一種直截了當的方式,我沒有遇到過。

非常感謝

export default class UserList extends Component { 
    constructor() { 
    super(); 
    this.userRef = firebase.database().ref().child('users') 
    this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}) 
    this.state = { 
     users: this.ds.cloneWithRows([]) 
    } 
    } 
    componentWillMount() { 
    //Checks my firebase database for the users and pushes it into the this._users array.... 
    this._users = [] 
    this.userRef.on('child_added', snap => { 
     this._users.push({ 
     user: snap.val().username, 
     isOnline: snap.val().isOnline, 
     isChatter: snap.val().isChatter, 
     uid: snap.val().uid 
     }); 
     //...which then gets passed into this function... 
     this.populateUsers(this._users); 
    }).bind(this); 
    } 
    populateUsers(nodes) { 
    //which then populates the state with the databases' users, which is then automatically rendered in the listview below 
    this.setState({users: this.ds.cloneWithRows(nodes)}); 
    } 
    _toChat(e) { 
    console.log('************ native target *************'); 
    console.log(e.target); 
    console.log('************ native target *************'); 
    } 
    render() { 
    return (
     <ListView 
     horizontal 
     enableEmptySections={true} 
     dataSource={this.state.users} 
     renderRow={d => <StatusSphere onPress={this._toChat} 
             uid={d.uid} 
             user={d.user} 
             isOnline={d.isOnline} 
             isChatter={d.isChatter}/>}/> 
    ) 
    } 
} 

回答

1

我不知道我理解你的問題,但是,

您可以使用箭頭函數使用額外的參數調用toChat方法。

onPress={(e)=>{this._toChat(e,d.uid)}} 
+0

哦,上帝,3小時的嘗試,這是答案..謝謝老兄! :) – Apswak

+1

不客氣,祝你好運! –

+0

不,這個記錄非常糟糕,所以人們繼續這樣做,並不斷推薦其他人這樣做。但是你不應該在JSX中使用'bind'或者arrow函數'​​'render',因爲它們每次都會創建一個新的函數。在這裏創建一個新的函數實際上會修改組件的狀態,正如您所知,React組件只會重新渲染具有狀態更改的組件。這是我們使用React的主要原因之一。這對於單個組件來說並不重要,但當需要生成組件數組時,會很快產生問題,例如使用map來生成ListItem。 – hippietrail

相關問題