markdown 如何安装和使用反应路由器(路由)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 如何安装和使用反应路由器(路由)相关的知识,希望对你有一定的参考价值。

# How to install and using react router

1. Install following packages

```
npm install react-router-dom --save
```

2. Usually you should create a separate component used for application routing

```js
import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';

import Home from './components/Home/home';
import Layout from './hoc/Layout/layout';
import News from './path/to/News';
import About from './path/to/About';


class Routes extends Component {
    render() {
        return (
            <Layout>
                <Switch>                    
                    <Route path="/" exact component={Home}/>
                    <Route path="/news/:id" exact component={News} />
                    <Route path="/videos/:id" exact component={About} />
                </Switch>
            </Layout>
        );
    }
}

export default Routes;
```

3. In your entry component, use `BrowserRouter`

```js
import React, { Component } from 'react';
import { BrowserRouter } from 'react-router-dom';
import Routes from './routes';

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <Routes/>
      </BrowserRouter>
    );
  }
}

export default App;
```

4. In any components you'd like to get routing works, use `Link` component

```js
import { Link } from 'react-router-dom';

<Link to="/" className="logo">Logo</Link>
```

### You can get routing value via props

以上是关于markdown 如何安装和使用反应路由器(路由)的主要内容,如果未能解决你的问题,请参考以下文章

markdown 反应路由器

markdown 反应-路由器页面不更新

markdown 反应路由器

markdown 反应路由器我的自定义导航练习

在反应中,当路由路径不同但组件相同时。如何防止重新安装?

如何从快递控制反应路由器