如果您将 Flatlist 属性 initialNumToRender 设置为 0,并检查您的项目是否在滚动离开时卸载,您可以轻松编写 componentDidMount 和 componentDidUnmount,如果 flatlist item index 小于 4 则触发.
如果这不起作用,我会尝试编写一个包装器组件来跟踪第四个组件的位置。
无论你的容器组件呈现什么
render() {
return (
<>
<Flatlist
initialNumToRender={4}
renderItem={({ index }) => (
<>
{index === 4 ? (
<PositionAwareView
setFourItemsInView={this.setFourItemsInView}
id={index}
>
<Item
setFourItemsInView={this.setFourItemsInView}
index={index}
/>
<PositionAwareView />
) : <Item />}
</>
)}
/>
{fourItemsInView ? <Stuff /> : null}
</>
)
}
- 将 Flatlist 属性
initialNumToRender 设置为 4,这样前四个项目就不会被卸载。
- 将函数
setFourItemsInView 作为道具传递给您的第 4 个项目,以修改容器组件(具有平面列表的那个)中的布尔值 fourItemsInView
- 在第 4 个项目组件触发器
setFourItemsInView(true) 的 componentDidMount 上。
- 编写一个包装器组件来跟踪名为
PositionAwareView 的位置,并在第4 项超出屏幕时调用setFourItemsInView。
这是 Typescript 的开始。
import * as React from 'react';
import { View } from 'react-native';
interface IPositionAwareViewProps {
id: string;
setFourItemsInView: any;
}
// interface IPositionAwareViewState {}
class PositionAwareView extends React.Component<IPositionAwareViewProps, {}> {
public state = {
ref: null
};
public ref: View | null;
public constructor(props: IPositionAwareViewProps) {
super(props);
this.ref = null;
}
public componentDidMount() {}
public render() {
return (
<View ref={ref => (this.ref = ref)} onLayout={this.onLayout}>
{this.props.children}
</View>
);
}
private onLayout = () => {
if (this.ref) {
this.ref.measure((x, y, width, height, pageX, pageY) => {
console.log(this.props.id, 'PositionAwareView x y X Y', x, y, pageX, pageY);
});
}
};
}
export default PositionAwareView;
您还需要注意不同的屏幕尺寸、凹槽(尤其是在 android 中)以及纵向与横向。
免责声明:不确定这将如何运作。也许最好忽略位置跟踪,只在另一个稍后项目的componentDidMount 中使用setFourItemsInView。