react-router-dom+typescript配置

今天在ts中配置react-router-dom時,遇到了各類坑,記錄一下。react

先說下react-router-dom中的兩種模式配置:BrowserRouter vs HashRouternpm

//BrowserRouter  (./router/index.tsx)
import * as React from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';

import index from '../pages/Index/index';
export default class RouteConfig extends React.Component {
  render(){
    return (
      <BrowserRouter basename="/pointsmall">
        <Switch>
          <Route path="/" exact component={index}></Route>
        </Switch>
      </BrowserRouter>
    )
  }
}
複製代碼
//HashRouter  (./router/index.tsx)
import React, { Component } from 'react';
import { HashRouter, Switch, Route } from 'react-router-dom';
import index from '../views/Index/index';
import test from '../views/Test/index';
import result from '../views/Result/index';
export default class RouteConfig extends Component {
  render(){
    return (
      <HashRouter>
        <Switch>
          <Route path="/" exact component={index}></Route>
          <Route path="/test/:id" component={test}></Route>
          <Route path="/result" component={result}></Route>
        </Switch>
      </HashRouter>
    )
  }
}
複製代碼
  1. 遇到的第一個坑:Could not find a declaration file for module 'react-router-dom'.

雖然咱們安裝了react-router-dombash

npm install --save react-router-dom
或者
yarn add react-router-dom
複製代碼

但要想typscript認識react-router-dom,咱們還要安裝對應的聲明文件react-router

npm i -D @types/react-router-dom
or
yarn add @types/react-router-dom -D
複製代碼
  1. 在根目錄的index.tsx中要修改對應的router信息

原來的代碼爲:dom

ReactDOM.render(<App />, document.getElementById('root'));
複製代碼

改成ui

//index.tsx
import Route from './router/index';
const render = (Component: any) => {
  ReactDOM.render(
      <Component />, 
      document.getElementById('root') as HTMLElement
  )
}
render(Route)
複製代碼

若是是js的話,改成以下:spa

//index.js
const render = Component =>{
  ReactDOM.render(

      <Component />,
      document.getElementById('root')

  )
}
render(Route)
複製代碼
相關文章
相關標籤/搜索