在我的父组件中我调用钩子useRef:const flatListRef = useRef(null);
,然后我想在子组件中使用这个flatListRef
。我试着在文档中这样做,但没有成功。当我调用toTop函数时,我得到:null is not an object (evaluating 'flatListRef.current.scrollToOffset')
这是父组件:
const BeautifulPlacesCards = ({navigation}: HomeNavigationProps<"BeautifulPlacesCards">) => {
const flatListRef = useRef(null);
const toTop = () => {
flatListRef.current.scrollToOffset(1)
}
const buttonPressed = () => {
toTop()
}
return(
<Carousel filteredData={filteredData} flatListRef={flatListRef}/>
)
}
是我的子组件:
const Carousel = forwardRef((filteredData, flatListRef) => {
return (
<AnimatedFlatList
ref={flatListRef}
/>
)
}
下面是一个工作示例:https://snack.expo.dev/@zvona/forwardref-example
关键需要:
- 你需要使用prop
ref
时传递它,而不是flatListRef
- 你需要从props中解构
filteredData
相关代码如下:
const Child = forwardRef(({ filteredData }, ref) => {
return (
<FlatList
ref={ref}
style={styles.flatList}
data={filteredData}
renderItem={({ item }) => (
<Text style={styles.item} key={`foo-${item}`}>
{item}
</Text>
)}
/>
);
});
const App = () => {
const flatListRef = useRef(null);
const toTop = () => {
flatListRef.current.scrollToOffset(1);
};
return (
<View style={styles.container}>
<Button title={'Scroll back'} onPress={toTop} />
<Child filteredData={[1,2,3,4,5,6]} ref={flatListRef} />
</View>
);
};