reactjs - ReactElement 类型转换

标签 reactjs typescript react-native react-navigation

这更像是一个 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/

相关文章:

reactjs - 如何在本地插件中将 Gatsbys wrapPageElement 与 Typescript 一起使用?

java - 需要在使用 android native 代码的 native react 中隐藏和禁用状态栏

html - 在 React 中使用表单数据上传图像

reactjs - 部署到 heroku 路径 ="/"路径 ="/favicon.ico"时出现问题

javascript - 我怎样才能让箭头函数工作?

react-native - 页面刷新后,React Native 中的导航不起作用

javascript - react 原生 TypeError : Network request failed with fetch()

javascript - 如何找出哪个包使用了不安全的 componentWillMount 方法?

html - 如何使用 WebView 加载 Google Play 页面?

typescript - 如何使用 ts-morph 获取对象文字属性