TypeScript如何获取父组件props精确类型?React Native useRef报错求助
TypeScript+React Native问题解答
一、useRef报错“Property 'scrollToLocation' does not exist on type 'never'”的原因与解决
错误原因
调用useRef()不传初始值时,TypeScript会自动推断其类型为RefObject<never>。由于current的类型是never,访问scrollToLocation属性自然会触发类型错误。
解决方法
明确指定useRef的类型为React Native中SectionList的实例类型,同时将初始值设为null:
import { SectionList } from 'react-native'; import { useRef } from 'react'; // 指定ref类型为SectionList,初始值为null const sectionListRef = useRef<SectionList>(null); // 使用时建议先判断current是否存在,避免空值调用 sectionListRef.current?.scrollToLocation({ sectionIndex: 0, itemIndex: 0, // 可添加viewOffset、viewPosition等配置项 });
二、如何获取父组件props的精确类型
有两种实用方式:
复用父组件已定义的Props接口:如果父组件已经显式声明了Props类型(如
interface或type),直接在子组件中导入使用即可:// 父组件中定义Props类型 interface ParentProps { username: string; isActive: boolean; } const ParentComponent = (props: ParentProps) => { // 组件逻辑 }; // 子组件直接复用该类型 const ChildComponent = (props: ParentProps) => { // 子组件逻辑 };用TypeScript工具类型提取:如果父组件未暴露Props类型,可使用
React.ComponentProps或React.ComponentPropsWithoutRef工具类型,从组件本身提取Props类型:import React from 'react'; import { ParentComponent } from './ParentComponent'; // 提取ParentComponent的所有Props类型(包含ref) type ParentProps = React.ComponentProps<typeof ParentComponent>; // 提取ParentComponent的Props类型并排除ref属性 type ParentPropsWithoutRef = React.ComponentPropsWithoutRef<typeof ParentComponent>; // 子组件使用提取后的类型 const ChildComponent = (props: ParentPropsWithoutRef) => { // 子组件逻辑 };
内容的提问来源于stack exchange,提问作者Mingyu Jeon
相关产品推荐
相关产品推荐

