【问题标题】:ReactElement type castingReactElement 类型转换
【发布时间】:2021-04-24 21:07:12
【问题描述】:

这更像是TypescriptReact 的问题,但为了全面披露,我会提到我在尝试使用react-navigation 创建自定义标头时来到这里。

我有一个简单的ImageButton(功能性)组件,它接受以下道具:

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:类型 '{ 透明:布尔值; }' 不可分配给类型“IntrinsicAttributes”。类型“IntrinsicAttributes”上不存在属性“透明”。

所以我的问题是,如何正确地将 ReactElement 转换为我的自定义组件 ImageButton 及其道具?

【问题讨论】:

    标签: reactjs typescript react-native react-navigation


    【解决方案1】:

    您的错误是因为您将其转换为的类型不接受任何参数或道具。

    这意味着,一个不带参数的函数返回 React.Element:

    () => ReactElement<ImageButtonProps>
    

    你想让它拿道具,所以你需要输入道具:

    (props: ImageButtonProps) => ReactElement<any>
    

    或者

    React.ComponentType<ImageButtonProps>
    

    此外,TypeScript 不支持对 ReactElement 进行类型检查,因此无需执行 ReactElement&lt;ImageButtonProps&gt;

    另见https://reactjs.org/blog/2015/12/18/react-components-elements-and-instances.html

    【讨论】:

      猜你喜欢
      • 2022-12-18
      • 2018-12-09
      • 2022-08-04
      • 2023-01-23
      • 2022-12-12
      • 1970-01-01
      • 2022-12-13
      • 2017-06-21
      • 2021-08-26
      相关资源
      最近更新 更多