使用 react-router-dom 配置路由
- 安装 react-router-dom
# 安装
yarn add react-router-dom
yarn add @types/react-router-dom
- 创建路由
// AppRouter.tsx
import React, {Component} from 'react';
import {HashRouter, Route, Switch} from 'react-router-dom';
import App from './App';
import Demo from './views/Demo';
class AppRouter extends Component<any, any> {
constructor(props: any) {
super(props);
this.state = {};
}
render(): any {
return (
<HashRouter>
<Switch>
<Route exact path="/" component={App} />
<Route path="/demo" component={Demo} />
</Switch>
</HashRouter>
);
}
}
export default AppRouter;
- 引入路由
// index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';
// import App from './App';
import AppRouter from './AppRouter';
ReactDOM.render(<AppRouter />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();