Typescript 和 React:在 React 中初始化 RouteComponentProps 成员

Typescript and React: Initializing RouteComponentProps members in React

我目前正在学习 Typescript 和 React,并且目前无法正确访问 props 的 'match' 成员。更具体地说,我在初始化从 RouteComponentProps 接口实现的变量时遇到了问题。

为了简化事情,我有以下 3 个文件和相应的组件(路径*)只渲染一个 header 和文本:

index.tsx

import React from 'react';
import ReactDOM from 'react-dom';

import App from './components/App';

ReactDOM.render(
  <React.StrictMode>
    <App/>
  </React.StrictMode>,
  document.getElementById('roots')
);

app.tsx

import React from 'react';
import {BrowserRouter as Router, Route, Switch, RouteComponentProps} from 'react-router-dom';

import Path1 from './Path1';
import Path2 from './Path2';
import Nav from './Nav'

class App extends React.Component<RouteComponentProps> {
  render(): JSX.Element{
    return (
      <Router>
        <div className="App">
          <Nav history={this.props.history} location={this.props.location} match={this.props.match}/>
          <Switch>
            <Route path="/" exact component={Home} name="Home"/>
            <Route path="/path1" exact component={Path1} name="path1"/>
            <Route path="/path2" exact component={Path2} name="path2"/>
          </Switch>
        </div>
      </Router>
    );
  }
}

export default App

Nav.tsx

import React from 'react';
import { Link, RouteComponentProps } from 'react-router-dom';

class Nav extends React.Component<RouteComponentProps>{
  render(): JSX.Element {
    return (
      <div className="Nav">
        {this.props.match.path}
        <ul className="NavLinks">
          <Link to="/">
            <li>Home</li>
          </Link>
          <Link to="/Path1">
            <li>Path1</li>
          </Link>
          <Link to="/Path2">
            <li>Path2</li>
          </Link>
        </ul>
      </div>
    );
  }
}

基本思路是,在单击每个 link 时,Nav 组件仅根据用户所在的页面更新页面顶部的文本。我之所以将导航条码放在原处,是因为它可以在将来添加更多路线时节省时间。

问题
我的问题是我需要在 index.tsx 中传递初始道具,但是我似乎找不到任何关于如何初始化接口 RouteComponentProps 中的道具的信息。或者,如果我做错了(或其他任何代码),请告诉我。我是 react/typescript 的新手,我想在第一时间学习正确的方法,避免 re-enforce 坏习惯。

关于做得更好,我建议使用功能组件而不是 class 组件。

功能组件也会让你使用react hooks。你可以从钩子中得到 locationhistorymatch

interface MatchParams {
  name: string
}

const App = (): React.ReactElement => 
  const history = useHistory()
  const location = useLocation()
  const match = useRouteMatch<MatchParams>()

  return (
    <Router>
      <div className="App">
        <Nav history={history} location={location} match={match} />