繁体   English   中英

反应,打字稿 - 无状态和普通组件的类型

[英]react, typescript - a type for both stateless and normal components

我正在尝试实现一个具有component属性的ProtectedRoute组件 - 它可以是无状态(纯)组件或正常的反应组件。

这些是我的类型:

export interface Props {
  isAuthenticated: boolean;
  component: React.PureComponent | React.Component;
  exact?: boolean;
  path: string;
}

这是我的 ProtectedRoute 组件:

import React from 'react';
import { Redirect, Route } from 'react-router-dom';

import { ROUTES } from '../../constants/routes';

import { Props } from './ProtectedRoute.types';

const ProtectedRoute = (props: Props) => {
  const { isAuthenticated, component: Component, ...rest } = props;
  return (
    <Route
      {...rest}
      children={props =>
        !isAuthenticated ? (
          <Redirect to={{ pathname: ROUTES.login, state: { from: props.location } }} />
        ) : (
          <Component {...props} />
        )
      }
    />
  );
};

export default ProtectedRoute;

我在这里收到以下错误:

类型错误:JSX 元素类型“组件”没有任何构造或调用签名。 TS2604

这是我如何使用它:

import React from 'react';

import { Route, Switch } from 'react-router-dom';
import ProtectedRoute from './ProtectedRoute';

import { ROUTES } from '../../constants/routes';

import Login from '../Login/Login';
const PlaceholderComponent = () => <div>This is where we will put content.</div>;
const NotFoundPlaceholder = () => <div>404 - Route not found.</div>;

const Routes = () => {
  return (
    <Switch>
      <Route exact path={ROUTES.login} component={Login} />
      {/* TODO protected route */}
      <ProtectedRoute exact path={ROUTES.list} component={PlaceholderComponent} />
      <ProtectedRoute exact path={ROUTES.procedure} component={PlaceholderComponent} />
      {/* catchall route for 404 */}
      <Route component={NotFoundPlaceholder} />
    </Switch>
  );
};

export default Routes;

并在此处收到以下错误:

类型 '() => Element' 不可分配给类型 'PureComponent<{}, {}, any> | 组件<{}, {}, any>'。 类型 '() => Element' 缺少类型 'Component<{}, {}, any>' 中的以下属性:context、setState、forceUpdate、render 等。 [2322]

这让我觉得我使用了不正确的类型定义。 什么是“正确”的方法来解决这个问题? 我的目的是检查ProtectedRoute总是将 React 组件作为component道具。

功能组件和类组件的类型是ComponentType

它应该是:

export interface Props {
  isAuthenticated: boolean;
  component: React.ComponentType;
  exact?: boolean;
  path: string;
}

可能找到了,但会保持打开状态,因为我不知道这是否是正确的解决方案:

export interface Props {
  isAuthenticated: boolean;
  component: React.ComponentClass<any> | React.StatelessComponent<any>;
  exact?: boolean;
  path: string;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM