当我使用 Intersection Observer 时,例如,当我的卡片在平面列表中重复时,我想设置一个阈值,以便观察者仅在屏幕上至少 70% 可见时识别每张卡片。
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 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;
例如,如果我设置了阈值,那么现在,第一张卡确实应该被视为“在视图中”,且
inView
函数中的 onChange
值为 true,因为它超过70%在屏幕上可见。但是,我希望第二张卡不被视为“可见”,因为它尚未达到 70% 可见性阈值。
有没有一种方法可以设置交叉点观察者的阈值,类似于网络观察者的设置?
https://github.com/zhbhun/react-native-intersection-observer
这是zhbhun/react-native-intersection-observer github
我想设置阈值
我创建了一个 HOC 函数来替换 React Native 中的 IntersectionObserver API。
https://www.npmjs.com/package/react-native-observable-list
直接使用FlatList的viewabilityConfig,就可以实现你提到的功能。
import { FlatList } from 'react-native';
import { observe } from 'react-native-observable-list';
const ObservableFlatList = observe(FlatList);
const Example1 = () => {
return (
<ObservableFlatList
viewabilityConfig={{
itemVisiblePercentThreshold: 70,
}}
// ...
/>
);
};