我正在尝试获取视图的滚动位置。但是Y偏移到页面的值与视图的位置无关。
ScrollView层次结构:
<ScrollView>
- MyComponent1
- MyComponent2
- SubView1
- SubView2
- <View> (Added ref to this view and passing Y offset value through props)
- MyComponent3
</ScrollView>
SubView2组件:
this.myComponent.measure( (fx, fy, width, height, px, py) => {
console.log('Component width is: ' + width)
console.log('Component height is: ' + height)
console.log('X offset to frame: ' + fx)
console.log('Y offset to frame: ' + fy)
console.log('X offset to page: ' + px)
console.log('Y offset to page: ' + py)
this.props.moveScrollToParticularView(py)
})
<View ref={view => { this.myComponent = view; }}>
我已经检查了方法SubView2
视图的确切位置onScroll
。但是确实与之匹配measure value
。我可以弄清楚这measure value
是错误的。
是ScrollView层次结构问题吗?
View
组件具有名为的属性onLayout
。您可以使用此属性获取该组件的位置。
onLayout
通过以下方式调用安装和布局更改:
{nativeEvent: { layout: {x, y, width, height}}}
一旦计算出布局,就会立即触发此事件,但是在接收到事件时,新的布局可能尚未反映在屏幕上,尤其是在进行布局动画时。
更新资料
onLayout
道具给父组件一个位置。这意味着要找到的位置SubView2
,您需要总计所有父级组件(MyComponent2
+ SubView1
+ SubView2
)。
样品
export default class App extends Component {
state = {
position: 0,
};
_onLayout = ({ nativeEvent: { layout: { x, y, width, height } } }) => {
this.setState(prevState => ({
position: prevState.position + y
}));
};
componentDidMount() {
setTimeout(() => {
// This will scroll the view to SubView2
this.scrollView.scrollTo({x: 0, y: this.state.position, animated: true})
}, 5000);
}
render() {
return (
<ScrollView style={styles.container} ref={(ref) => this.scrollView = ref}>
<View style={styles.view}>
<Text>{'MyComponent1'}</Text>
</View>
<View style={[styles.view, { backgroundColor: 'blue'}]} onLayout={this._onLayout}>
<Text>{'MyComponent2'}</Text>
<View style={[styles.view, , { backgroundColor: 'green'}]} onLayout={this._onLayout}>
<Text>{'SubView1'}</Text>
<View style={[styles.view, { backgroundColor: 'yellow'}]} onLayout={this._onLayout}>
<Text>{'SubView2'}</Text>
</View>
</View>
</View>
</ScrollView>
);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句