使用create-react-app 快速構建 React 開發環境以及react-router 4.x路由配置

來源:互聯網
上載者:User

標籤:root   匹配   執行   style   環境   開發   設定檔   接下來   工作   

  create-react-app 是來自於 Facebook,通過該命令我們無需配置就能快速構建 React 開發環境。

  create-react-app 自動建立的項目是基於 Webpack + ES6 

  執行命令如下:

npm install create-react-app -g  // 全域安裝create-react-app,如果不想全域安裝,則不要-g。可能會很慢,可以使用cnpm來安裝create-react-app my-app  // my-app是項目名cd my-app  npm start  // 啟動項目

 

  這裡按部就班來執行就行了,沒啥可說的。

 

  接下來要說的是react-router 4.x路由配置。

  之前是按照react-router 4.x以下版本來配置,結果發現老報錯,死活運行不出來,網上查資料一看,坑爹的,原來3.x與4.x路由配置是完全不一樣的。

  4.x的版本需要安裝react-router-dom

  

  準備工作:安裝react-router-dom

   npm install react-router-dom --save // --save 會把依賴包名稱添加到 package.json 檔案 dependencies 鍵下,運行時依賴 

  

  (1)、在src檔案夾下建立components檔案夾,用來存放組件。例如我的是這樣的:

        

 

    其中index.js是路由設定檔。

 

  (2)、在路由設定檔index.js中依次匯入要使用的組件以及路由需要使用的組件。如我的配置是這樣的:    

import React, { Component } from ‘react‘;import ReactDOM from ‘react-dom‘;import {    BrowserRouter as Router,    Route,    Link}from ‘react-router-dom‘;import ‘./index.css‘; import App from ‘./components/App‘;  // 匯入App組件import About from ‘./components/About‘; // 匯入About組件import Inbox from ‘./components/Inbox‘; // 匯入Inbox組件import registerServiceWorker from ‘./registerServiceWorker‘;export default class Hello extends Component{    render(){        return (            <Router>                <div>                    <ul className="nav">      <li><Link to="/">App</Link></li>      <li><Link to="/About">About</Link></li>      <li><Link to="/Inbox">Inbox</Link></li>       </ul>                    <hr />                    <Route exact path="/" component={App} />                    <Route path="/About" component={About} />                    <Route path="/Inbox" component={Inbox} />                </div>            </Router>        )    }}ReactDOM.render(<Hello />, document.getElementById(‘root‘));registerServiceWorker();

  其中exact是用來”/”做唯一的匹配。如果沒有這個的話,在匹配其他的同時也會匹配到當前

  運行效果如下:

      

 

      

 

      

 

 

 

 

  

  

  

 

使用create-react-app 快速構建 React 開發環境以及react-router 4.x路由配置

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.