使用型別化引數進行路由

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Route, BrowserRouter as Router, Link, match } from 'react-router-dom';

// define React components for multiple pages
class Home extends React.Component<any, any> {
  render() {
    return (
      <div>
        <div>HOME</div>
        <div><Link to='/details/id123'>Goto Details</Link></div>
      </div>);
  }
}

interface DetailParams {
  id: string;
}

interface DetailsProps {
  required: string;
  match?: match<DetailParams>;
}

class Details extends React.Component<DetailsProps, any> {
  render() {
    const match = this.props.match;
    if (match) {
      return (
        <div>
          <div>Details for {match.params.id}</div>
          <Link to='/'>Goto Home</Link>
        </div>
      );
    } else {
      return (
        <div>
          <div>Error Will Robinson</div>
          <Link to='/'>Goto Home</Link>
        </div>
      )
    }
  }
}

ReactDOM.render(
  <Router>
    <div>
      <Route exact path="/" component={Home} />
      <Route exact path="/details/:id" component={(props) => <Details required="some string" {...props} />} />
    </div>
  </Router>

  , document.getElementById('root')
);

為了保護具有所需屬性 requiredDetails 元件的型別安全性,<Route> 定義定義了一個基於匿名函式的元件,它組成了 <Details> 型別的新元件並指定了 required 屬性。

擴充套件運算子用於將傳遞給基於匿名函式的元件的 props 重新應用到組合的 <Details> 元件上。

match 屬性被定義為可選,因為它由 react-router 動態填充,遺憾的是,我們無法將其定義為必需屬性。這意味著稍後訪問值時需要型別保護。