react使用路由

Posted on 2019-07-21 11:26  猫头唔食鱼  阅读(244)  评论(0编辑  收藏  举报

1.安装

npm i react-router-dom --save

 

2.引入

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

 

3.使用

app.js

import React, { Component } from 'react';
import{
  BrowserRouter as Router ,Route,Link
} from 'react-router-dom'
import Home from './Home'
import News from './News'
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {  }
  }
  render() { 
    return (  
      // 根组件包含Router标签,Router标签包含Link标签和Route标签
      <div>
        <Router>
          <ul>
            <li>
              <Link to="/">首页</Link>
            </li>
            <li>
              <Link to="/news">新闻</Link>
            </li>
          </ul>
          <Route exact component={Home} path="/"></Route>
          <Route component={News} path="/news"></Route>
        </Router>
      </div>
    );
  }
}
 
export default App;