I'm facing an issue in which I need to change header text position from left to centre when user begin scroll and back to left if user scroll to top. But I unable to find solution for. I'm using scrollview which have a lot of content inside it. Can anyone tell me how to do that?
CodePudding user response:
You can find a solution here :
<ScrollView
onScroll={({nativeEvent})=>{
if(isCloseToTop(nativeEvent)){
//do something
}
if(isCloseToBottom(nativeEvent)){
//do something
}
}}
>
...contents
</ScrollView>
isCloseToBottom({layoutMeasurement, contentOffset, contentSize}){
return layoutMeasurement.height contentOffset.y >= contentSize.height - 20;
}
ifCloseToTop({layoutMeasurement, contentOffset, contentSize}){
return contentOffset.y == 0;
}
CodePudding user response:
Try this way
import React, { useState, useEffect } from "react";
function Example() {
const [scrollPosition, setScrollPosition] = useState(-1);
useEffect(() => {
// console.log("scrollPosition: ", scrollPosition);
if (scrollPosition === 0) {
// condition is true when scroll on top
}
}, [scrollPosition]);
const getscrollposition = (e) => {
const y = e.nativeEvent.contentOffset.y;
setScrollPosition(y);
};
return (
<ScrollView
onMomentumScrollEnd={getscrollposition}
scrollEventThrottle={16}
>
.....
</ScrollView>
);
}