ฉันมีองค์ประกอบ scrollView และฉันต้องการเรียกใช้ฟังก์ชันการโทรกลับที่แตกต่างกันหากผู้ใช้เลื่อนลงหรือขึ้น
ฉันจะเรียกเหตุการณ์ scrollView เลื่อนขึ้นหรือลงใน React Native ได้อย่างไร [ปิด]
คำตอบ (1)
คุณสามารถใช้ onScroll prop เพื่อรับการแจ้งเตือนทุกครั้งที่ผู้ใช้เลื่อน
เพื่อให้บรรลุผลตามที่ต้องการ คุณเพียงแค่ต้องจัดเก็บตำแหน่ง และหากมีการอัพเดต ให้ตรวจสอบว่าตำแหน่ง y เปลี่ยนแปลงด้วยจำนวนพิกเซลที่เป็นบวก (ลง) หรือด้วยจำนวนพิกเซลที่ติดลบ (ขึ้น)
เนื่องจากองค์ประกอบ React ที่ใช้งานได้มีลักษณะดังนี้:
function MyComponent() {
// we use a ref here in order to store the value between rendering without triggering an update (like useState would)
const scrollYRef = useRef(0)
return (
<ScrollView
onScroll={(event) => {
// 0 means the top of the screen, 100 would be scrolled 100px down
const currentYPosition = event.nativeEvent.contentOffset.y
const oldPosition = scrollYRef.current
if(oldPosition < currentYPosition) {
// we scrolled down
} else {
// we scrolled up
}
// save the current position for the next onScroll event
scrollYRef.current = currentYPosition
}}
....
/>
)
}
person
Maddis
schedule
05.11.2020