react路由使用
1:插件添加cnpm install react-router-dom-S2:app.js书写import React, { Component } from 'react';//路由的2种形式: hash(HashRouter) , H5的historyApi(BroswerRouter)是路由的容器,是组件,要包在路由的外面import { HashRouter ...
·
1:插件添加
cnpm install react-router-dom -S
2:app.js书写
import React, { Component } from 'react';
//路由的2种形式: hash(HashRouter) , H5的historyApi(BroswerRouter)是路由的容器,是组件,要包在路由的外面
import { HashRouter as Router,Route} from 'react-router-dom'
function Home() {
return <p>首页</p>
}
function Profile() {
return <p>个人中心</p>
}
function User() {
return <p>用户中心</p>
}
class App extends Component {
render() {
return (
<Router>
<div>
{/*exact确切为/时,才会匹配。否则在下面2个路由中,都会显示第一个路由*/}
<Route path='/' exact={true} component={Home}></Route>
<Route path={'/profile'} component={Profile}></Route>
<Route path={'/user'} component={User}></Route>
</div>
</Router>
);
}
}
export default App;
3:组件使用方法
(1)项目基本结构,其他Profile, User模块跟home模块基本一致
(2)app.js使用
import React, { Component } from 'react';
//路由的2种形式: hash(HashRouter) , H5的historyApi(BroswerRouter)是路由的容器,是组件,要包在路由的外面
import { HashRouter as Router,Route} from 'react-router-dom'
// import {Home} from './containers/Home',写法错误,错误原因如下解释
import Home from './containers/Home'
import Profile from './containers/Profile'
import User from './containers/User'
class App extends Component {
render() {
return (
<Router>
<div>
{/*exact确切为/时,才会匹配。否则在下面2个路由中,都会显示第一个路由*/}
<Route path='/' exact={true} component={Home}></Route>
<Route path={'/profile'} component={Profile}></Route>
<Route path={'/user'} component={User}></Route>
</div>
</Router>
);
}
}
export default App;
更多推荐
所有评论(0)