react.js從入門到精通(六)——路由的使用


對路由的理解

在pc端頁面之間的切換,我們大多使用a鏈接、location等操作。 
在react.js開發中,我們采用組件化操作,一個頁面就是一個組件。所以頁面和頁面之間的跳轉就相當於是組件和組件之間的跳轉。 
我們知道react.js是一種單頁面項目開發,就是在一個主頁面的基礎上存放各種子頁面。這就好像一根網線連接路由器,而路由器能分出很多根網線連接大量的電腦。所以我們將單頁面項目的頁面跳轉稱為路由。 
在第一篇放出的框架中,我們介紹過專門用來管理路由的文件——routes.js文件。

1、使用Link進行路由跳轉

(1)routes.js中的配置

import React from 'react' import { Route, IndexRoute } from 'react-router' import MyScreen from './containers/MyScreen'; import { App, Home, } from './containers' export default ( <Route path="/" component={App}> <IndexRoute component={Home}/> <Route path="my"> <IndexRoute component={MyScreen}/> </Route> </Route> );
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

注意:這里需要使用react-router功能模塊,一般都是框架中自帶的,如果沒有可使用npm進行下載使用(第一篇分享的框架的package.json中已經囊括了常用的功能資源)。

(2)Home.js中的代碼

import React,{ Component } from 'react' import MyScreen from "./MyScreen"; import { Link } from 'react-router' class Home extends Component { constructor(props) { super(props); this.state = { }; } render() { return ( <div style={{width:"100%",height:"300px",fontSize:"20px"}}> <Link to="/my"> <div id="div1" style={{width:"100%",height:"100px",backgroundColor:"#ff0",lineHeight:"100px",textAlign:"center"}}>點擊跳轉</div> </Link> </div> ) } } export default Home
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

(3)MyScreen.js中的代碼:

import React,{ Component } from 'react' class MyScreen extends Component { constructor(props) { super(props); this.state = { }; } render() { return ( <div style={{width:"100%",height:document.documentElement.clientHeight,fontSize:"12px",backgroundColor:"#0ff",textAlign:"center",lineHeight:"100px"}} onClick={()=>this.click()}> 這是MyScreen界面 </div> ) } click=()=>{ alert("點擊到了!!!!"); }; } export default MyScreen
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

2、使用push的方式進行路由跳轉

這一種相對於Link方法更加常用。

Home.js代碼

import React,{ Component } from 'react' import MyScreen from "./MyScreen"; import { Link } from 'react-router' class Home extends Component { static contextTypes = { router: React.PropTypes.object }; constructor(props) { super(props); this.state = { }; } render() { return ( <div style={{width:"100%",height:"300px",fontSize:"20px"}}> <div id="div1" style={{width:"100%",height:"100px",backgroundColor:"#ff0",lineHeight:"100px",textAlign:"center"}} onClick={()=>this.click()}>點擊跳轉</div> </div> ) } click=()=>{ this.context.router.push("/my"); }; } export default Home
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

下面這種方法,首先要增加靜態變量,里面進行路由的一些配置。然后直接通過.router.push進行調用。其他兩個文件與上面的一樣,不加修改。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM