Monday, May 20, 2024
53
rated 0 times [  54] [ 1]  / answers: 1 / hits: 16541  / 6 Years ago, fri, june 1, 2018, 12:00:00

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 Hierarchy:



<ScrollView>
- MyComponent1
- MyComponent2
- SubView1
- SubView2
- <View> (Added ref to this view and passing Y offset value through props)
- MyComponent3
</ScrollView>


SubView2 Component:



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; }}>


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.



Is it ScrollView hierarchy problem?


More From » react-native

 Answers
8

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.




Update



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).



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>
);
}
}

[#54295] Tuesday, May 29, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devlin

Total Points: 474
Total Questions: 113
Total Answers: 100

Location: Sweden
Member since Fri, Apr 16, 2021
3 Years ago
;