gpt4 book ai didi

reactjs - ReactElement 类型转换

转载 作者:行者123 更新时间:2023-12-04 03:42:09 27 4
gpt4 key购买 nike

这更像是一个 TypescriptReact问题,但为了全面披露,我会提到我在尝试使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com