我正在尝试获取视图的滚动位置。但价值为页面的 Y 偏移量这与视图的位置无关。
滚动视图层次结构:
<ScrollView>
- MyComponent1
- MyComponent2
- SubView1
- SubView2
- <View> (Added ref to this view and passing Y offset value through props)
- MyComponent3
</ScrollView>
子视图2组件:
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; }}>
我已经检查了 a 的确切位置SubView2
查看onScroll
方法。但确实与measure value
。我能弄清楚measure value
是错的。
是ScrollView层次结构问题吗?
View
组件有一个属性称为onLayout。您可以使用此属性来获取该组件的位置。
onLayout
在安装和布局更改时调用:
{nativeEvent: { layout: {x, y, width, height}}}
一旦计算出布局,就会立即触发此事件,
但当时新的布局可能还没有反映在屏幕上
收到事件,特别是如果布局动画处于
进步。
Update
onLayout
prop 为父组件提供了一个位置。这意味着找到SubView2
,您需要获得所有父组件的总和(MyComponent2
+ SubView1
+ SubView2
).
Sample
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>
);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)