这更像是一个 Typescript
和 React
问题,但为了全面披露,我会提到我在尝试使用 react-navigation 创建自定义 header 时结束了这里。 .
我有一个简单的 ImageButton
(功能)组件,它接受以下 Prop :
export interface ImageButtonProps extends TouchableOpacityProps {
transparent?: boolean;
}
我的自定义标题看起来(大致)是这样的:export default function Header(props: StackHeaderProps) {
const options = props.scene.descriptor.options;
const HeaderRight = options.headerRight as (() => ReactElement<ImageButtonProps>);
return (<HeaderRight transparent={true}/>); // <-- Typescript complains here
}
可以安全地假设 options.headerRight
将始终返回 ImageButton
,这实际上呈现得很好。唯一的问题是属性transparent
始终未定义,并且 Typescript 也会引发以下错误:TS2322: Type '{ transparent: boolean; }' is not assignable to type 'IntrinsicAttributes'. Property 'transparent' does not exist on type 'IntrinsicAttributes'.
所以我的问题是,我怎样才能正确地转换
ReactElement
到我的自定义组件,ImageButton
和它的 Prop ?
最佳答案
您的错误是因为您将其转换为的类型不带任何参数或 Prop 。
这意味着,一个不带参数的函数返回 React.Element:
() => ReactElement<ImageButtonProps>
你想让它拿 Prop ,所以你需要输入 Prop :(props: ImageButtonProps) => ReactElement<any>
或者React.ComponentType<ImageButtonProps>
此外,TypeScript 不支持对 ReactElement 进行类型检查,因此无需执行 ReactElement<ImageButtonProps>
.另见 https://reactjs.org/blog/2015/12/18/react-components-elements-and-instances.html
关于reactjs - ReactElement 类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65810593/