![](/img/trans.png)
[英]In React Native, how can I get the Y offset of a custom component and then scroll a ScrollView to its position?
[英]React Native - How to get Y Offset Value of a view from ScrollView?
我試圖獲得視圖的滾動位置。 但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; }}>
我已經在onScroll
方法上檢查了SubView2
視圖的確切位置。 但確實與measure value
匹配。 我可以弄清楚measure value
是錯誤的。
它是ScrollView層次結構問題嗎?
View
組件有一個名為onLayout
的屬性。 您可以使用此屬性來獲取該組件的位置。
onLayout
在安裝和布局更改時調用:
{nativeEvent: { layout: {x, y, width, height}}}
一旦計算了布局,就會立即觸發此事件,但是在接收到事件時,新布局可能尚未反映在屏幕上,尤其是在布局動畫正在進行時。
更新
onLayout
prop為父組件提供一個位置。 這意味着要找到SubView2
的位置,您需要獲得所有父組件( MyComponent2
+ SubView1
+ SubView2
)的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>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.