react 腳手架創建項目步驟

前序:react 腳手架創建項目,分react高低版兩種,接下來具體看實施

react低版本

1、全局環境:npm install -g create-react-app

創建項目:create-react-app 項目名

創建好之後,根據提示執行,如果沒有提示還是看package.json 文件/2

2、使用create-react-app 創建項目,裏面安裝的react的版本默認的是高板,在低版本中使用需要將react降成低版本 npm i [email protected] [email protected] -D

3、安裝react的路由

npm i react-router@2 --save-dev

然後去創建目錄 (components,css,img)

4、引入主要組件對象

import {Router,Route,hashHistory,IndexRoute} from 'react-router'

Router  -----路由對象
Route  ------規則對象
Link   ------導航標籤
hashHistory ---路由方向管理

5、寫組件和配置路由,低版本中的路由配置是在入口index.js文件中設置,

<Router history={hashHistory}>
        <Route path='/about' component={About}></Route>
        Route 的屬性有path和component
</Router>

高react版本

高版的路由配置位置和方式與低版不同

npm install -g create-react-app 全局環境

create-react-app 項目名 創建項目

生成項目後,按如下步驟

1、安裝依賴 不需要指定版本,默認最新

npm i react-router react-router-dom --save-dev

2、引入主要組件對象

import {BrowserRouter as Router,Route,Link,Redirect} from ‘react-router-dom’;

寫組件和路由:

路由是在本組件寫的,使用的是Router +Route , Router只包含一個根節點

3、書寫結構在組件內部,不需要寫在render中,Router組件有且只有一個跟節點,除了路由組件,可以寫入其他標籤

默認 Route所在的位置爲路由組件顯示的容器(tips:Link寫在Router內部形成路由結構)

<Router>
	<div>
		<Link to="/home">首頁</Link>
		<Link to="/about">關於</Link>
		<Route path="/home" component={Home}></Route>
		<Route path="/about" component={About}></Route>
	</div>
</Router>

4、路由重定向 通過 Redirect組件對象,設置to屬性

<Redirect to="/about"/>

需要和Switch 配合使用

5、路由參數傳遞 -----------------比低版多了state

/a/1 ---this.props.match.params.id               --------params 傳參

/a?id=1---this.props.location.query.id		------query傳參

/a --  this.props.location.state     		---------state傳參
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章