如何将自定义React组件ModalText指定为其他组件的Prop类型?
自定义组件数组的TypeScript类型与渲染问题
问题背景
开发带自定义样式的GenericModal组件时,希望传入ModalText组件数组作为props并渲染,要求明确指定类型为ModalText而非泛型React.FC。
遇到的错误
- 直接用
ModalText[]定义props类型:
type Props = PropsWithChildren<{ paneContents: ModalText[]; }>
报错:ModalText refers to a value but is being used as a type here. Did you mean typeof ModalText
- 使用
typeof ModalText[]后渲染:
<View> {props.paneContents} </View>
报错:TS2769: No overload matches this call. '(props: ViewProps | Readonly<ViewProps>): View', gave the following error. Type 'FC<Props>[]' is not assignable to type 'ReactNode'.
附ModalText组件代码:
import React, { PropsWithChildren } from 'react'; import { View, Text, ViewStyle } from 'react-native'; // 假设style为已定义的样式对象 const style = { container: {}, modalHeader: {}, modalText: {} }; type ModalTextProps = PropsWithChildren<{ style?: ViewStyle; header?: string; body?: string; }>; const ModalText: React.FC<ModalTextProps> = (props) => { return ( <View style={[style.container, props.style]}> {props.header && <Text style={style.modalHeader}>{props.header}</Text>} {props.body && <Text style={style.modalText}>{props.body}</Text>} </View> ); };
解决方案
方案1:传入组件的元素实例
React渲染的是JSX元素实例,而非组件函数本身。将paneContents类型定义为React.ReactElement<ModalTextProps>[],既明确是ModalText的实例,又能直接渲染:
修改GenericModal的props类型:
import React, { PropsWithChildren } from 'react'; import { View } from 'react-native'; import { ModalTextProps } from './ModalText'; type GenericModalProps = PropsWithChildren<{ paneContents: React.ReactElement<ModalTextProps>[]; }>; const GenericModal: React.FC<GenericModalProps> = (props) => { return ( <View> {props.paneContents} </View> ); };
使用示例:
<GenericModal paneContents={[ <ModalText header="标题1" body="内容1" />, <ModalText header="标题2" body="内容2" /> ]} > {/* 子元素 */} </GenericModal>
方案2:传入组件与对应props(动态渲染场景)
若需动态生成ModalText,可传入组件+props的数组组合,类型定义为Array<[typeof ModalText, ModalTextProps]>,渲染时遍历生成实例:
修改GenericModal的props类型:
type GenericModalProps = PropsWithChildren<{ paneContents: Array<[typeof ModalText, ModalTextProps]>; }>; const GenericModal: React.FC<GenericModalProps> = (props) => { return ( <View> {props.paneContents.map(([Component, componentProps], index) => ( <Component key={index} {...componentProps} /> ))} </View> ); };
使用示例:
<GenericModal paneContents={[ [ModalText, { header: "标题1", body: "内容1" }], [ModalText, { header: "标题2", body: "内容2" }] ]} > {/* 子元素 */} </GenericModal>
错误原因说明
ModalText是组件值(函数)而非类型,直接用作类型会报错;typeof ModalText得到的是组件函数的类型,但React无法直接渲染函数,只能渲染JSX实例。ReactNode类型包含JSX元素、字符串等,但不包含组件函数数组,因此typeof ModalText[]无法兼容ReactNode类型。
内容的提问来源于stack exchange,提问作者Reagankm
相关产品推荐
相关产品推荐

