我正在使用FlatList,我想創建一個Ref,以便在按下一個按鈕時能夠滾動FlatList。
問題是,我正在使用Typescript,我遇到了一個型別錯誤,我無法解決。
問題是,我如何為FlatList ref創建一個介面?
這里我們有一個我正在做的例子。
let flatListRef = useRef()。
<FlatList。
ref={flatListRef} // Error Here
data={store.data}
.../>
<Button。
onPress={()=>
flatListRef.current.scrollToIndex({index:index})
} />
我遇到的型別錯誤是當我把Ref設定到FlatList中的時候
該錯誤說:overload 1 of 2, '(props: FlatListProps<{ data: string; type: number; id: number; }> | Readonly<FlatListProps<{ data: string; type: number; id: number; }>>)。) FlatList<...>',給出了以下錯誤。 型別'MutableRefObject'不能賦值給型別'LegacyRef<FlatList<{ data: string; type: number; id: number; }>> |。 undefined'。 型別'MutableRefObject'不能分配給型別'RefObject<FlatList<{ data: string; type: number; id: number; }>> '。 屬性'current'的型別不兼容。 型別'undefined'不能分配給型別'FlatList<{ data: string; type: number; id: number; }> | null'.
。Overload 2 of 2, '(props: FlatListProps<{ data: string; type: number; id: number; }>, context: any)。FlatList<{ data: string; type: number; id: number; }>, context: any): number; id: number; }>',給出了以下錯誤。 型別'MutableRefObject'不能分配給型別'LegacyRef<FlatList<{ data: string; type: number; id: number; }> > | undefined'.
當我在創建時將型別設定為ref時,錯誤并沒有解決,類似于:
interface ListProps {
data: string;
type: 數字。
id: 數字。
}
let flatListRef = useRef<ListProps>()
或者當我創建useRef鉤子時,我需要將資料結構或其他東西作為initialValue傳遞給它?
uj5u.com熱心網友回復:
你的flatListRef是一個ref到FlatList的實體。 因此,這就是你想用來作為你的通用型別引數的東西。
對DOM元素的參考期望一個null的初始值,而不是undefined,所以你也需要解決這個問題。
const flatListRef = useRef<FlatList>(null) 。
當你訪問參考時,你要使用可選的鏈式?.,以防.current仍然是null。
flatListRef.current?scrollToIndex({index})。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/326344.html
標籤:
