React路由

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方法跳转页面。

 

posted @ 2019-09-23 20:09  枯桑  阅读(163)  评论(0编辑  收藏  举报