【问题标题】:Correctly typing a component which is passed as a prop正确键入作为道具传递的组件
【发布时间】:2020-08-21 12:32:18
【问题描述】:

我曾想过包装react-router Path 组件。我正在尝试在渲染中使用 component 道具,但出现错误:

JSX 元素类型“组件”没有任何构造或调用 签名.ts(2604)

代码如下:

export interface Props {
  component: RouteProps['component'];
  path: RouteProps['path'];
  canShow: boolean;
}

const ProtectedRoute: React.FunctionComponent<Props> = ({
  component: Component,
  canShow,
  ...rest
}) => {
  return (
    <Route
      {...rest}
      render={
        props => canShow
          ? (<Component {...props} />)
          : null
      }
    />
  );
};

export default connect(mapStateToProps)(ProtectedRoute);

如何根据我拥有的类型渲染它?

【问题讨论】:

    标签: reactjs typescript react-router


    【解决方案1】:

    问题

    如果您查看RouteProps['component'] 的类型,您会发现它实际上包含undefined,因为component 属性是可选的。您会收到有关“无构造或调用签名”的错误,因为您无法构造或调用您的 Component 变量而不确保它不是 undefined

    选项 1:检查道具

    在使用 JSX 调用之前,您可以确保 Component 有效

    render={
      props => (canShow && Component)
        ? (<Component {...props} />)
        : null
    }
    

    选项 2:需要一个组件

    您还可以更改 Props 的类型,以确保只能使用有效的 component 属性调用 ProtectedRoute。这两者的结果相同,并且会通过确保component 不能是undefined 来消除错误。

    export interface Props {
      component: Required<RouteProps>['component'];
      path: RouteProps['path'];
      canShow: boolean;
    }
    
    export interface Props {
      component: NonNullable<RouteProps['component']>;
      path: RouteProps['path'];
      canShow: boolean;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-20
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 2021-09-08
      • 1970-01-01
      • 2020-03-22
      相关资源
      最近更新 更多