簡體   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