初步学习React Router 4.0

React Router 4.0 是react官方推荐的路由库。4是已经正式发布的最新版本。

初始化项目启动之后:

npm run eject 弹出配置文件。自定义配置webpack

查看下package.json中是不是有react-router-dom,没有安装即可

注意:安装最新版本的react   命令行:npm install --save react@next react-dom@next   

@next即安装最新的版本

"react-router-dom": "^4.2.2"

如下图配置路由   引入 BrowserRouter ,Route ,Switch

BrowserRouter 包裹整个应用、整个应用只有一个

里面只有一个子节点。多个要用div包裹

注意:多个路由  要加个参数  switch 只渲染命匹配的第一个组件

  exact   实现精确匹配(匹配到第一个就不往下继续匹配)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

import React from 'react';

import ReactDOM from 'react-dom';

import { BrowserRouter ,Route ,Switch } from 'react-router-dom';

import './index.css';

import App from './App';

import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(

    <div>

        <BrowserRouter>

            <Switch>

                <Route path='/' component={App} exact />

            </Switch>

        </BrowserRouter>

    </div>

    , document.getElementById('root'));

registerServiceWorker();

  

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

import React from 'react';

import ReactDOM from 'react-dom';

import { BrowserRouter ,Route ,Switch } from 'react-router-dom';

import './index.css';

import App from './App';

import Newsdetail from './containers/newsdetail/index';

import Newslist from './containers/newslist/index';

import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(

    <div>

        <BrowserRouter>

            <Switch>

                <Route path='/' component={App} exact />

                <Route path='/newsdetail' component={ Newsdetail }/>

                <Route path='/newslist' component={ Newslist }/>

            </Switch>

        </BrowserRouter>

    </div>

    , document.getElementById('root'));

registerServiceWorker();

 第一种方式:

this.props.history.push

 

 第二种方式 link的方式。相当于a跳转

<Link to='/newslist'></Link>

 3 子组件中拥有路由的方法:

得到的是undefined  在子组件中没有路由。如果想拥有路由

先安装:babel-plugin-transform-decorators-legacy

配置文件中如下;

页面中使用@

 

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

import React from 'react';

import { withRouter } from 'react-router-dom';

@withRouter

class Subnews extends React.Component{

    constructor(props){

        super(props);

        this.clickhandler=this.clickhandler.bind(this);

    }

    clickhandler(){

        console.log(this.props.history);

        this.props.history.push('/');

    }

    render() {

        return (

            <div>

                这是Subnews

                <button onClick={this.clickhandler}>点击跳转到首页</button>

            </div>

        );

    }

}

export default Subnews;

 4:URL参数。可以用冒号标识参数

在newpage中获取参数:

这是参数:{this.props.match.params.id}

原文:https://www.cnblogs.com/kelly2017/p/8022045.html

猜你喜欢

转载自blog.csdn.net/weixin_39939012/article/details/83546567