React-router-dom
1.安装
npm install react-router-dom --save-dev //这里可以使用cnpm代替npm命令
2. 基本操作
home.js
import React from 'react'; export default class Home extends React.Component { render() { return ( <div> <a>去detail</a> </div> ) } }
detail.js
import React from 'react'; export default class Home extends React.Component { render() { return ( <div> <a>回到home</a> </div> ) } }
Router.js
import React from 'react'; import {HashRouter, Route, Switch} from 'react-router-dom'; import Home from '../home'; import Detail from '../detail'; const BasicRoute = () => ( <HashRouter> <Switch> <Route exact path="/" component={Home}/> <Route exact path="/detail" component={Detail}/> </Switch> </HashRouter> ); export default BasicRoute;
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import Router from './router/router'; ReactDOM.render( <Router/>, document.getElementById('root') );
3.通过a标签跳转
home.js
import React from 'react'; export default class Home extends React.Component { render() { return ( <div> <a href='#/detail'>去detail</a> </div> ) } }
detail.js
import React from 'react'; export default class Home extends React.Component { render() { return ( <div> <a href='#/'>回到home</a> </div> ) } }
4. 通过函数跳转
1.首先在router.js中添加
import {HashRouter, Route, Switch, hashHistory} from 'react-router-dom'; <HashRouter history={hashHistory}>
2. 在home.js
import React from 'react'; export default class Home extends React.Component { constructor(props) { super(props); } render() { return ( <div> <a href='#/detail'>去detail</a> <button onClick={() => this.props.history.push('detail')}>通过函数跳转</button> </div> ) } }
在a标签下面添加一个按钮并加上onClick事件,通过this.props.history.push这个函数跳转到detail页面。在路由组件中加入的代码就是将history这个对象注册到组件的props中去,然后就可以在子组件中通过props调用history的push方法跳转页面。