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}/>}/>
)
}
}
哦,上帝,3小时的尝试,这是答案..谢谢老兄! :) – Apswak
不客气,祝你好运! –
不,这个记录非常糟糕,所以人们继续这样做,并不断推荐其他人这样做。但是你不应该在JSX中使用'bind'或者arrow函数''render',因为它们每次都会创建一个新的函数。在这里创建一个新的函数实际上会修改组件的状态,正如您所知,React组件只会重新渲染具有状态更改的组件。这是我们使用React的主要原因之一。这对于单个组件来说并不重要,但当需要生成组件数组时,会很快产生问题,例如使用map来生成ListItem。 – hippietrail