React Native - 如何从 ScrollView 获取视图的 Y 偏移值?
我正在尝试获取视图的滚动位置.但是 Y 到页面的偏移量 的值与视图的位置无关.
I am trying to get the scroll position of a view. But the value for Y offset to page which is not related to the view's position.
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; }}>
我在 onScroll
方法上检查了 SubView2
视图的确切位置.但确实与 measure value
匹配.我可以弄清楚 measure value
是错误的.
I have checked the exact position of a SubView2
view on onScroll
method. But did match with the measure value
. I can figure it out the measure value
is wrong.
是不是ScrollView层次问题?
Is it ScrollView hierarchy problem?
推荐答案
View
组件有一个名为 onLayout
.您可以使用此属性来获取该组件的位置.
View
component has a property called onLayout
. You can use this property to get the position of that component.
onLayout
在装载和布局更改时调用:
Invoked on mount and layout changes with:
{nativeEvent: { layout: {x, y, width, height}}}
计算完布局后立即触发此事件,但当时新的布局可能还没有体现在屏幕上接收到事件,尤其是在布局动画处于进展.
This event is fired immediately once the layout has been calculated, but the new layout may not yet be reflected on the screen at the time the event is received, especially if a layout animation is in progress.
更新
onLayout
属性给父组件一个位置.这意味着要找到SubView2
的位置,你需要得到所有父组件的总和(MyComponent2
+ SubView1
+ SubView2
).
onLayout
prop gives a position to the parent component. This means to find the position of SubView2
, you need to get total of all the parent components (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>
);
}
}
相关文章