二、添加路由
2019-12-10 本文已影响0人
风之伤_3eed
1、安装react-router-dom
npm i react-router-dom
注:文档可查看react-router-dom
2、修改src/App.tsx文件代码如下
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
} from "react-router-dom";
import {
Login, Home
} from './pages';
import "./App.css";
const App = () => {
return (
<Router>
<Switch>
<Route exact path="/login" component={Login} />
<Route exact path="/" component={Home} />
</Switch>
</Router>
);
};
export default App;
3、在src下新建pages文件夹(该文件夹存放页面)
注:有dom元素的新建文件后缀名为tsx没有的则为ts
pages文件夹目录为
.
├── home
│ └── index.tsx
├── index.ts
└── login
└── index.tsx
index.ts文件为了方便引入组件统一导出
export { default as Home } from './home';
export { default as Login } from './login';
home页面(src/pages/home/index.tsx)
import React from 'react';
import { Link } from 'react-router-dom';
const Home = () => {
return (
<div>
Home
<p><Link to="/login">login</Link></p>
</div>
)
}
export default Home
login页面(src/pages/login/index.tsx)和home页面类似(仅为切换路由展示区别)
import React from 'react';
import { Link } from 'react-router-dom';
const Login = () => {
return (
<div>
Login
<p><Link to="/home">home</Link></p>
</div>
)
}
export default Login
4、直接在地址栏访问可以看到home,切换路由为login可以看到login
home页面
image.png
login页面
image.png