步行骑水牛 發表於 2020-3-15 08:28:00

React 路由基本配置

<p>app.js</p>
<div class="cnblogs_code">
<pre><span style="color: rgba(0, 128, 0, 1)">/*</span><span style="color: rgba(0, 128, 0, 1)">

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、复制官网文档根组件里面的内容进行修改(加载的组件要提前引入)


         &lt;Router&gt;

                &lt;Link to="/"&gt;首页&lt;/Link&gt;

                &lt;Link to="/news"&gt;新闻&lt;/Link&gt;

                &lt;Link to="/product"&gt;商品&lt;/Link&gt;


               &lt;Route exact path="/" component={Home} /&gt;
               &lt;Route path="/news" component={News} /&gt;   
               &lt;Route path="/product" component={Product} /&gt;   
         &lt;/Router&gt;


         exact表示严格匹配
         
</span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">



import React, { Component } from </span>'react'<span style="color: rgba(0, 0, 0, 1)">;

import { BrowserRouter as Router, Route, Link } from </span>"react-router-dom"<span style="color: rgba(0, 0, 0, 1)">;


import </span>'./assets/css/index.css'<span style="color: rgba(0, 0, 0, 1)">

import Home from </span>'./components/Home'<span style="color: rgba(0, 0, 0, 1)">;
import News from </span>'./components/News'<span style="color: rgba(0, 0, 0, 1)">;
import Product from </span>'./components/Product'<span style="color: rgba(0, 0, 0, 1)">;

class App extends Component {

render() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> (
      </span>&lt;Router&gt;
          &lt;div&gt;         

            &lt;header className="title"&gt;
            
                &lt;Link to="/"&gt;首页&lt;/Link&gt;

                &lt;Link to="/news"&gt;新闻&lt;/Link&gt;

                &lt;Link to="/product"&gt;商品&lt;/Link&gt;

            &lt;/header&gt;


               &lt;br /&gt;
               &lt;hr /&gt;
      
               &lt;br /&gt;
      
      
            &lt;Route exact path="/" component={Home} /&gt;
            &lt;Route path="/news" component={News} /&gt;   
            &lt;Route path="/product" component={Product} /&gt;               
          &lt;/div&gt;
      &lt;/Router&gt;
<span style="color: rgba(0, 0, 0, 1)">    );
}
}

export </span><span style="color: rgba(0, 0, 255, 1)">default</span> App;</pre>
</div>
<p>&nbsp;</p>

</div>
<div id="MySignature" role="contentinfo">
    最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!<br><br>
来源:https://www.cnblogs.com/loaderman/p/11556639.html
頁: [1]
查看完整版本: React 路由基本配置