react中的路由--react-router-dom

1、进入到项目目录,打开命令行,安装react-router-dom,指令:npm install react-router-dom --save-dev

2、在一个js文件中引入react-router-dom, import { HashRouter, Route, Switch } from 'react-router-dom'

3、在render函数中return路由结构,如下:

<HashRouter>
    <Switch>
        <Route path='/' component={ Home } /> 
        <Route path='/home' component={ Home } /> 
        <Route path='/search' component={ Search } /> 
        <Route path='/mine' component={ Mine } /> 
    </Switch>
</HashRouter>

4、将这个js文件暴露出去,在index.js中引入,之后在index.js中ReactDOM.render(<Router/>,document.getElementById('root')); 至此,当我们在地址栏中输入home、search或mine时,页面都会跳到其路由对应的组件

5、以函数的形式进行路由跳转,在a标签上绑定onClick事件,通过this.props.history.push这个函数跳转

posted @ 2019-09-23 21:09  冰棍Gal  阅读(205)  评论(0编辑  收藏  举报