React Native TypeScript如何获取作为props传入的组件的Props类型
实现方案
你需要通过 TypeScript 泛型捕获传入组件的类型,结合 React 内置工具类型自动推导对应组件的 Props,完整实现如下:
import React from 'react'; import styled from 'styled-components/native'; import type { ComponentProps, ComponentType } from 'react'; // 泛型Props定义:捕获传入组件类型,自动提取对应Props type WrapperProps<T extends ComponentType<any>> = { component: T; } & ComponentProps<T>; // 样式组件移到外部定义,避免每次渲染重建导致组件卸载重挂 const StyledWrapper = styled.View` background-color: red; `; // 泛型组件实现 const Component = <T extends ComponentType<any>>({ component: PassedComponent, ...restProps }: WrapperProps<T>) => { // 用styled-components的as属性动态渲染传入的组件,透传所有Props return <StyledWrapper as={PassedComponent} {...restProps} />; };
用法验证
和你要求的用法完全一致,TypeScript 会自动识别对应组件的专属Props:
// 自动识别Pressable的onPress属性,无类型报错 <Component component={Pressable} onPress={() => console.log("sds")} /> // 自动识别Image的source属性,无类型报错 <Component component={Image} source={{ uri: 'https://example.com/img.png' }} />
注意事项
原代码中将styled组件定义在函数组件内部的写法存在问题:每次组件重渲染都会生成新的styled组件实例,会导致子组件状态丢失、性能下降,统一移到组件外部定义即可解决。
内容的提问来源于stack exchange,提问作者plutolaser
相关产品推荐
相关产品推荐

