how to access react-native listview child components through ref?
class MyComponent extends Component {
constructor() {
super();
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows(['row 1', 'row 2', 'row 3', 'row 4', 'row 5', 'row 6']),
};
}
onTap() {
console.log(this.refs)
/* After getting touchComponent refs below block of code has to be executed.
that.refs.touchComponent.measure((ox, oy, width, height, px, py) => {
this.setState({
isVisible: true,
buttonRect: {x: px, y: py, width: width, height: height}
});
});
*/
}
render() {
return (
<ListView ref="listView"
dataSource={this.state.dataSource}
renderRow={(rowData) => <TouchableHighlight ref="touchComponent" onPress={this.onTap.bind(this)}><Text>{rowData}</Text></TouchableHighlight>}
/>
);
}
}
console.log(this.refs)
prints Object {listView: Object}
how can i access TouchableHighlight
component ref?
I gone through React Native: Refs in ListView and React Native - get refs of custom components in listview from renderRow but i don't understand how they are doing.
You cant access refs through the string way of adding refs inside ListView you have to use the callback technique to apply refs
<ListView ref="listView"
dataSource={this.state.dataSource}
renderRow={(rowData) => <TouchableHighlight ref={(TouchableHighLight) => { this.button = TouchableHighLight; }} onPress={this.onTap.bind(this)}><Text>{rowData}</Text></TouchableHighlight>}
/>
But most probably even after getting the ref you wont be able to access the measure method. To obtain pageX and pageY you can pass the touch event with the onPress and use nativeEvent to obtain the pageX and pageY like this ,you can obtain width and height using measureInWindow method:-
onPress={(event) => this.onTap(event)}
method definition could be something like this:-
onTap(evnt) {
var py=evnt.nativeEvent.pageY
var px=evnt.nativeEvent.pageX
console.log(this.refs)
this.button.measureInWindow(x,y,width,height)
this.setState({
isVisible: true,
buttonRect: {x: x, y: y, width: width, height: height}
});
});
}