Jan*_*ima 12 typescript reactjs react-native react-hooks
我正在使用 FlatList,我想创建一个引用,以便在按下一个按钮时能够滚动 FlatList。
问题是我正在使用 Typescript,并且遇到一种我无法解决的类型错误。
问题是,如何为 FlatList 引用创建接口?
这里有一个我正在做的事情的例子。
let flatListRef = useRef();
<FlatList
ref={flatListRef} // Error Here
data={store.data}
... />
<Button
onPress={() =>
flatListRef.current.scrollToIndex({index:index})
} />
Run Code Online (Sandbox Code Playgroud)
我遇到的类型错误是当我将 ref 设置为 FlatList 时
错误说:
重载 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; 类型:数字;身份证号; }>> | 不明确的'。类型“MutableRefObject”不可分配给类型“RefObject<FlatList<{ data: string; 类型:数字;身份证号; }>>'。“当前”属性的类型不兼容。类型“undefined”不可分配给类型“FlatList<{ data: string;” 类型:数字;身份证号; }> | 无效的'。
重载 2 of 2, '(props: FlatListProps<{ data: string; type: number; id: number; }>, context: any): FlatList<{ data: string; 类型:数字;身份证号; }>',给出了以下错误。类型“MutableRefObject”不可分配给类型“LegacyRef<FlatList<{ data: string; 类型:数字;身份证号; }>> | 不明确的'。
当我在创建它时将类型设置为 ref 时,错误无法解决,如下所示:
interface ListProps {
data: string;
type: number;
id: number;
}
let flatListRef = useRef<ListProps>()
Run Code Online (Sandbox Code Playgroud)
或者,当我创建 useRef 挂钩时,我是否需要传递数据结构或其他内容作为初始值?
Lin*_*ste 45
你flatListRef是一个ref实例FlatList。这就是您想要用作泛型类型参数的内容。
对 DOM 元素的引用需要初始值null而不是undefined,因此您还需要修复该问题。
const flatListRef = useRef<FlatList>(null);
Run Code Online (Sandbox Code Playgroud)
当您访问 ref 时,您将需要使用可选链接,?.以防.currentis still null。
flatListRef.current?.scrollToIndex({index})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8366 次 |
| 最近记录: |