[英]How do I correctly use ReactJS Reach Router with TypeScript & ESLint?
我正在嘗試在使用 TypeScript 和 ESLint 的項目中使用 Reach Router 實現僅客戶端路由。 這是我最初的實現:
// src/pages/app/[...].tsx
import { Router, Redirect, useLocation } from '@reach/router';
import * as React from 'react';
import BrowseMain from '../../components/BrowseMain';
import Layout from '../../components/Layout';
import UploadMain from '../../components/UploadMain';
import * as styles from '../../styles/[...].module.scss';
const IndexPage = () => {
const currLocation = useLocation();
return (
<Layout>
<main className={styles.indexMain}>
<Router basepath="/app">
{['/', '/browse', '/browse/'].map((path) => <BrowseMain key={path} path={path} />)}
{['/upload', '/upload/'].map((path) => <UploadMain key={path} path={path} />)}
{/* Redirect 404 */}
<Redirect noThrow default from={currLocation.pathname} to="/" />
</Router>
</main>
</Layout>
);
};
export default IndexPage;
// src/components/BrowseMain.tsx
import * as React from 'react';
import '../styles/BrowseMain.module.scss';
import Main from './Main';
const BrowseMain = () => <Main>Browse</Main>;
export default BrowseMain;
// UploadMain is similar to BrowseMain, so they are facing the same issue here.
// src/components/Main.tsx
import * as React from 'react';
import '../styles/Main.module.scss';
type MainProps = {
children: string,
};
const Main = ({ children }: MainProps) => <>{children}</>;
export default Main;
此時,TypeScript 在[...].tsx
中的BrowseMain
和UploadMain
路由上拋出以下錯誤:
TS2322:鍵入'{鍵:字符串; 路徑:字符串; }' 不可分配給類型“IntrinsicAttributes”。 類型“IntrinsicAttributes”上不存在屬性“路徑”。
按照到達路由器的文檔使用 TypeScript ,我做了以下更改:
import { RouteComponentProps } from '@reach/router';
import * as React from 'react';
import '../styles/BrowseMain.module.scss';
import Main from './Main';
const BrowseMain = (props: RouteComponentProps) => <Main>Browse</Main>;
export default BrowseMain;
這解決了之前的 linting 錯誤,但是引發了兩個新錯誤:
TS6133:聲明了“道具”,但從未讀取其值。
ESLint:“道具”已定義但從未使用過。(@typescript-eslint/no-unused-vars)
在這一點上,我被困住了。 我嘗試了兩種不同的方法,但它們都引發了 linting 錯誤:
// ESLint: Unexpected empty object pattern.(no-empty-pattern)
const BrowseMain = ({}: RouteComponentProps) => (
// ESLint: '_' is defined but never used.(@typescript-eslint/no-unused-vars)
const BrowseMain = (_: RouteComponentProps) => (
我覺得如果你這樣做,我就該死,如果你現在不這樣做,我就該死。 為不會使用的道具聲明顯式類型的正確方法是什么?
您可以使用 generics 指定道具。 在你的情況下,它看起來像:
const BrowserMain: React.FC<RouteComponentProps> = () => <Main>Browse</Main
但是不鼓勵使用 React.FC,因此您也可以使用 typescript 調用簽名
type BrowserMainFC = {
(props: RouteComponentProps): JSX.Element
}
const BrowseMain: BrowserMainFC = () => <div />
查看此資源: https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/function_components/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.