14.React路由 react-router4.x的基本配置

原创
2019/01/15 10:14
阅读数 129

exact表示严格匹配

跟组件


/*

  react路由的配置:
    1、找到官方文档 https://reacttraining.com/react-router/web/example/basic

    2、安装  cnpm install react-router-dom --save


    3、找到项目的根组件引入react-router-dom

       import { BrowserRouter as Router, Route, Link } from "react-router-dom";

    4、复制官网文档根组件里面的内容进行修改  (加载的组件要提前引入)


         <Router>

                <Link to="/">首页</Link>

                <Link to="/news">新闻</Link>

                <Link to="/product">商品</Link>


               <Route exact path="/" component={Home} />
               <Route path="/news" component={News} />    
               <Route path="/product" component={Product} />   
         </Router>


         exact表示严格匹配
         
*/



import React, { Component } from 'react';

import { BrowserRouter as Router, Route, Link } from "react-router-dom";


import './assets/css/index.css'

import Home from './components/Home';
import News from './components/News';
import Product from './components/Product';

class App extends Component {

  render() {
    return (
        <Router>
          <div>           

              <header className="title">
              
                <Link to="/">首页</Link>

                <Link to="/news">新闻</Link>

                <Link to="/product">商品</Link>

              </header>


               <br />
               <hr />
      
               <br />
      
      
              <Route exact path="/" component={Home} />
              <Route path="/news" component={News} />    
              <Route path="/product" component={Product} />                 
          </div>
      </Router>
    );
  }
}

export default App;

 

首页组件

import React, { Component } from 'react';

class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {  };
    }
    render() {
        return (
            
            <div>

                我是home组件
            </div>
        );
    }
}

export default Home;

 

新闻组件

import React, { Component } from 'react';

class News extends Component {
    constructor(props) {
        super(props);
        this.state = {  };
    }
    render() {
        return (
            
            <div>

                我是新闻组件
            </div>
        );
    }
}

export default News;

产品组件

import React, { Component } from 'react';

class Product extends Component {
    constructor(props) {
        super(props);
        this.state = {  };
    }
    render() {
        return (
            
            <div>

                我是商品组件
            </div>
        );
    }
}

export default Product;

 

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部