如何访问 react-native listview通过 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)
版画 Object {listView: Object}
我如何访问
TouchableHighlight
组件引用? 我经历了React Native: Refs in ListView和 React Native - get refs of custom components in listview from renderRow但我不明白他们是怎么做的。
最佳答案
您无法通过在 ListView 中添加 refs 的字符串方式访问 refs,您必须使用回调技术来应用 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>}
/>
但很可能即使在获得 ref 之后,您也无法访问测量方法。要获取 pageX 和 pageY,您可以通过 onPress 传递触摸事件并使用 nativeEvent 像这样获取 pageX 和 pageY,您可以使用 measureInWindow 方法获取宽度和高度:-
onPress={(event) => this.onTap(event)}
方法定义可能是这样的:-
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}
});
});
}
关于react-native - 如何通过ref访问react-native listview子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41719551/