如何在zhbhun/react-native-intersection-observer中设置观测阈值?
在react-native-intersection-observer中设置可见度阈值
react-native-intersection-observer支持设置可见度阈值,和Web版Intersection Observer用法一致,通过给<InView>组件添加threshold属性即可实现需求——当卡片至少70%可见时,onChange回调的inView才会返回true。
修改核心代码
只需在<InView>组件中添加threshold={0.7}属性:
const Item: React.FC<ItemProps> = ({title}) => ( // 设置threshold为0.7,即元素70%可见时触发inView状态变更 <InView threshold={0.7} onChange={(inView: boolean) => console.log(inView, title)} > <View style={{borderWidth: 1, height: 300, margin: 20}}> <Text>{title}</Text> </View> </InView> );
完整代码
import {View, Text} from 'react-native'; import React, {useRef} from 'react'; import {SafeAreaView} from 'react-native-safe-area-context'; import { IOScrollView, IOScrollViewController, InView, IOFlatListController, IOFlatList, } from 'react-native-intersection-observer'; interface ItemProps { title: string; } const DATA = [ {id: '1', title: 'First Item'}, {id: '2', title: 'Second Item'}, {id: '3', title: 'Third Item'}, {id: '4', title: 'Forth Item'}, {id: '5', title: 'Fifth Item'}, {id: '6', title: 'Sixth Item'}, {id: '7', title: 'Seventh Item'}, {id: '8', title: 'Eighth Item'}, {id: '9', title: 'Ninth Item'}, {id: '10', title: 'Tenth Item'}, ]; const Item: React.FC<ItemProps> = ({title}) => ( <InView threshold={0.7} onChange={(inView: boolean) => console.log(inView, title)} > <View style={{borderWidth: 1, height: 300, margin: 20}}> <Text>{title}</Text> </View> </InView> ); const Observer: React.FC = () => { const scrollViewRef = useRef<IOFlatListController>(null); const renderItem = ({item}: {item: {id: string; title: string}}) => ( <Item title={item.title} /> ); return ( <SafeAreaView style={{backgroundColor: 'orange', flex: 1}}> <IOFlatList style={{borderWidth: 2, backgroundColor: 'white'}} ref={scrollViewRef} data={DATA} renderItem={renderItem} keyExtractor={item => item.id} /> </SafeAreaView> ); }; export default Observer;
说明
threshold属性接受0到1之间的数值,代表元素可见区域占自身总区域的比例阈值- 设置为0.7后,只有当卡片的可见部分超过自身面积的70%时,
onChange才会返回inView: true,完全匹配你描述的需求
内容的提问来源于stack exchange,提问作者sooori kyu
相关产品推荐
相关产品推荐

