簡體   English   中英

React TypeScript:路由位置和子屬性的正確類型

[英]React TypeScript: Correct types for Route location and children properties

我有一個路由器可以傳遞位置和子項的道具,但我不知道這些道具的正確類型是什么。

這是使用 react-router-dom 的路由器...

import React, { useReducer } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { globalContext, setGlobalContext } from './components/context';
import { Layout } from './components/layout';
import { defaultState, globalReducer } from './components/reducer';
import { Home } from './routes/home';
import { NotFound } from './routes/notFound';

const Router: React.FC = () => {
  const [global, setGlobal] = useReducer(globalReducer, defaultState);
  return (
    <setGlobalContext.Provider value={{ setGlobal }}>
      <globalContext.Provider value={{ global }}>
        <BrowserRouter>
          <Route
            render={({ location }) => (
              <Layout location={location}>
                <Switch location={location}>
                  <Route exact path='/' component={Home} />
                  <Route component={NotFound} />
                </Switch>
              </Layout>
            )}
          />
        </BrowserRouter>
      </globalContext.Provider>
    </setGlobalContext.Provider>
  );
};

export { Router };

在布局組件內部,我有一個用於位置和子項的界面,但是因為我不知道這些的正確類型,所以我最終使用了任何類型,然后我的 linter 出現了問題。

import React from 'react';

interface PropsInterface {
  children: any;
  location: any;
}

const Layout: React.FC<PropsInterface> = (props: PropsInterface) => {
  return (
    <div>
      <p>{props.location}</p>
      <p>{props.children}</p>
    </div>
  );
};

export { Layout };

我得到的錯誤是“任何”的類型聲明失去了類型安全性。 考慮用更精確的類型替換它。 (無)tslint(1)

我可以從 import import { useLocation } from 'react-router-dom';獲取位置import { useLocation } from 'react-router-dom';

您正在尋找的Route接口可以在@types/react-router定義中找到。

在您的項目中安裝它后,您應該能夠使用如下界面消除該 TS 錯誤:

// Layout.tsx

import { RouteProps } from "react-router";

interface ILayoutProps {
  location: RouteProps["location"];
  children: RouteProps["children"];
}

const Layout: React.FC<ILayoutProps> = (props: ILayoutProps) => {
  return <div>{props.children}</div>;
};

請記住, location是一個對象,因此 React 不會讓您像以前那樣渲染它。

這是工作示例的鏈接: https : //codesandbox.io/s/zealous-snyder-yw9dg


另一種選擇是使用Partial接口,但這將使所有ILayoutProps可選:

interface ILayoutProps extends Partial<RouteProps> {}

您還可以使用react-router-dom公開的RouteComponentProps找到這些類型的接口。 嘗試:

import { RouteComponentProps } from "react-router-dom";

並將其映射到您的組件,如下所示:

// Layout.tsx

import { RouteComponentProps } from "react-router-dom";

const Layout: React.FC<RouteComponentProps> = (props) => {
  return <div>{props.children}</div>;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM