react學(xué)習(xí)第三天筆記

react路由

模塊

  • 下載react-router模塊,版本3.0.5站粟;
  • 解構(gòu)賦值:Router,Route,hashHistory;如:import {Router,Route,hashHistory} from "react-router";

簡單路由

  • 通過Router包裹Route標(biāo)簽黍图;地址欄中通過http://localhost:8080/#/app;渲染app頁面奴烙;
 import React,{Component} from "react";
 import ReactDom,{render} from "react-dom";
 import {Router,Route,hashHistory} from "react-router";
 
 //Router:整體路由助被;
 //Route:單個路由;
 import App from "./component/App";
 import Contact from "./component/Contact";
 class Index extends Component{
     render(){
         return(
             <Router history={hashHistory}>
                 <Route path="/app" component={App}>
                 <Route path="/contact" component={Contact}/>
             </Router>
         )
     }
 }
 render(<Index/>,document.getElementById("app"));

路由嵌套

  • 在Route標(biāo)簽中繼續(xù)嵌套Route標(biāo)簽切诀;
 class Index extends Component{
     render(){
         return(
             <Router history={hashHistory}>
                 <Route path="/" component={App}>
                     <Route path="contact" component={Contact}/>
                     <Route path="about" component={About}/>
                 </Route>
             </Router>
         )
     }
 }

導(dǎo)航菜單的跳轉(zhuǎn)

  • react-router中結(jié)構(gòu)賦值出Link和IndexLink;如import {Link,IndexLink} from "react-router";
  • 代碼:<Link to="/"></Link><IndexLink to="/shou">xx</IndexLink>

路由的激活效果狀態(tài)

  • activeStyle 行內(nèi)樣式揩环;
    • 模板:activeStyle={{color:"red",fontSize:"20px"}}
    • 注意:內(nèi)容使用雙花括號;
  • activeClassName 非行間樣式幅虑;引入外界的css文件丰滑,然后設(shè)置class名;如:activeClassName="current";

IndexLink

  • 一般情況下倒庵,當(dāng)我們訪問"/about"的時候褒墨,會默認(rèn)激活兩個路由;
    • "/"對應(yīng)的組件擎宝;
    • "about"對應(yīng)的組件郁妈;
  • 如果使用了IndexLink,就可以只激活我們要找的那個路由;

導(dǎo)航欄小實例

  • 知識點
    • this.props.children在點擊每個li標(biāo)簽后认臊,才能獲取,并顯示锄奢,如果失晴,不跳轉(zhuǎn),則拿到的children為null拘央,點擊哪個li標(biāo)簽涂屁,拿到的children就為哪個標(biāo)簽;
    • 正常點擊情況下灰伟,會訪問兩個組件拆又,一個是"/"對應(yīng)的組件,一個是"about"對應(yīng)的組件栏账;
    • Link和IndexLink的區(qū)別帖族;
    • 行間樣式activeStyle和非行間樣式activeClassName的設(shè)置;
    • this.props.children的獲取值挡爵;
  • 代碼:
    • index.js代碼
     import React,{Component} from "react";
     import ReactDom,{render} from "react-dom";
     import {Router,Route,hashHistory} from "react-router";
     
     //Router:整體路由竖般;
     //Route:單個路由;
     import App from "./component/App";
     import Contact from "./component/Contact";
     import About from "./component/About";
     class Index extends Component{
         render(){
             return(
                 <Router history={hashHistory}>
                     <Route path="/" component={App}>
                         <Route path="contact" component={Contact}/>
                         <Route path="about" component={About}/>
                     </Route>
                 </Router>
             )
         }
     }
     render(<Index/>,document.getElementById("app"));
    
    • App.js代碼
     import React,{Component} from "react";
     import {Link,IndexLink} from "react-router";
     
     import "./index.css";
     class App extends Component{
         render(){
             const style={
                 color:"blue",
                 fontSize:"30px"
             };
             return(
                 <div>
                     <h1>這是導(dǎo)航菜單</h1>
                     <ul>
                         <li>
                             <IndexLink to="/" activeClassName="current">這是首頁</IndexLink>
                         </li>
                         <li>
                             <Link to="/contact" activeStyle={{color:"red",fontSize:"20px"}}>這是Contact</Link>
                         </li>
                         <li>
                             <Link to="/about" activeStyle={style}>這是關(guān)系我們</Link>
                         </li>
                     </ul>
                     {/*點擊誰茶鹃,拿到的children就為哪個標(biāo)簽*/}
                     {this.props.children}
                 </div>
             )
         }
     }
     export default App;
    

路由參數(shù)

  • 通過在Route標(biāo)簽設(shè)置path屬性涣雕,通過":"來設(shè)置艰亮;在子組件About中通過"this.props.params.xx"獲取挣郭;
    • 代碼:<Route path="/about/:a/:b" component={About}/>迄埃;
    • index.js代碼:
     class Index extends Component{
         render(){
             return(
                 <Router history={hashHistory}>
                     <Route path="/" component={App}>
                         <Route path="contact" component={Contact}/>
                         <Route path="about/:a" component={About}/>
                     </Route>
                 </Router>
             )
         }
     }
    
    • About.js代碼:
     class About extends Component{
         render(){
             return(
                 <div>
                     <h2>關(guān)于我們 {this.props.params.a}</h2>
                 </div>
             )
         }
     }
    

重定向

  • 通過react-router中的屬性Redirect;解構(gòu)賦值出來;
    • 代碼:<Redirect from="about" to="about/react111"></Redirect>
    • from:指用戶輸入的地址兑障; to:指的是跳轉(zhuǎn)到哪里侄非;

打印的this.props的參數(shù)

  • 如下代碼中,在index.js中設(shè)置Route路由旺垒,跳轉(zhuǎn)About.js文件彩库,在About.js中打印this.props后得到的是一個對象;對象中有多個屬性:
    • children:
    • location:解析地址欄
    • params
    • route
    • router:屬性值為對象先蒋,對象中存在goBack骇钦,goforward等屬性,對應(yīng)屬性值為函數(shù)竞漾,注意:調(diào)用函數(shù)時必須保證this為實例眯搭;
      • 調(diào)用goBack()函數(shù):<button onClick={()=>{this.props.router.goBack()}}>go Back</button>
      • 回退功能也可以使用browserHistory.goBack()

默認(rèn)路由

  • react-router中的屬性IndexRoute,即默認(rèn)打開的頁面;
    • 解構(gòu)賦值:import {IndexRoute} from "react-router";
    • 當(dāng)跳轉(zhuǎn)"/"時业岁,會默認(rèn)顯示兩個組件鳞仙,App和Home組件;
    • 代碼:
     class Index extends Component{
         render(){
             return(
                 <Router history={hashHistory}>
                     <Route path="/" component={App}>
                         <IndexRoute component={Home}/>
                         <Route path="contact" component={Contact}/>
                         <Route path="about/:a" component={About}/>
                         <Redirect from="about" to="about/react111"/>
                     </Route>
                 </Router>
             )
         }
     }
    

history

  • history屬性類型
    • 解構(gòu)賦值react-router;如:import {hashHistory,browserHistory} from "react-router"
    • hashHistory:在地址欄中會存在"#",如http://localhost:8080/#/contact
      • 不需要你配置服務(wù)器即可使用
      • 不支持服務(wù)端渲染
      • 不建議在生產(chǎn)環(huán)境使用
    • browserHistory:在地址欄中不會存在"#",如:http://localhost:8080/contact
      • 需要配置路由器:在package.json文件中的"script"下的"start"笔时,后面添加--history-api-fallback
       "scripts": {
           "test": "echo \"Error: no test specified\" && exit 1",
           "start": "webpack-dev-server --progress --colors --content-base dist --history-api-fallback",
           "build": "webpack --progress --colors"
         }
      
      • 通過URL變化來改變路由的棍好,調(diào)用的是瀏覽器的History
      • 一般用于線上生產(chǎn)環(huán)境

路由跳轉(zhuǎn)

  • Link:利用to來跳轉(zhuǎn)地址,進而打開對應(yīng)的模塊允耿;如:<Link to="/">...</Link>
  • browserHistory.push():路由跳轉(zhuǎn)
    1. 需要拼接地址
      • 如果是表單的情況下借笙,我們需要對表單中的form添加一個onSubmit事件
      • 事件中需要通過e.preventDefault(),阻止表單默認(rèn)提交的事件较锡;
      • 通過e.target.elements來獲取表單下對應(yīng)的子節(jié)點业稼;
    2. 需要檢查路由,因為拼接的路由形式為:/about/xxx/xxx蚂蕴,所以低散,如果拿到參數(shù),必須把路由設(shè)置為/about/:xx/:xx;
    3. 在路由對應(yīng)的模塊中骡楼,通過this.props.params.xx來獲取對應(yīng)的參數(shù)熔号;
    • 代碼:
      • index.js中路由設(shè)置代碼:
      lass Index extends Component{
          render(){
              return(
                  <Router history={browserHistory}>
                      <Route path="/" component={App}>
                          <IndexRoute component={Home}/>
                          <Route path="contact" component={Contact}/>
                          <Route path="/about/:a/:b" component={About}/>
                          {/*重定向*/}
                          <Redirect from="about" to="about/react111/d"/>
                      </Route>
                  </Router>
              )
          }
      }
      
      • App.js代碼:
      import React,{Component} from "react";
      import {Link,IndexLink,browserHistory} from "react-router";
      
      import "./index.css";
      class App extends Component{
          data=(e)=>{
              e.preventDefault();
              //e.target拿到的是form標(biāo)簽,e.target.elements拿到的是所有的表單標(biāo)簽
              var username=e.target.elements[0].value;
              var info=e.target.elements[1].value;
              //拼接地址
              var path=`/about/${username}/${info}`;
              //利用browserHistory.push()鸟整,設(shè)置路由
              browserHistory.push(path);
          };
          render(){
              return(
                  <div>
                      <h1>這是導(dǎo)航菜單</h1>
                      <ul>
                          <li>
                              <form onSubmit={this.data}>
                                  <p>
                                      用戶名:
                                      <input type="text" name="username"/>
                                  </p>
                                  <p>
                                      用戶名信息:
                                      <input type="text" name="info"/>
                                  </p>
                                  <p>
                                      <input type="submit" value="提交參數(shù)"/>
                                  </p>
                              </form>
                          </li>
                      </ul>
                      {/*點擊誰跨嘉,拿到的children就為哪個標(biāo)簽*/}
                      {this.props.children}
                  </div>
              )
          }
      }
      export default App;
      
  • this.context.router.push():路由跳轉(zhuǎn)
    • 與browserHistory.push()用法相同,就是所用的代碼不同;
     data=(e)=>{
         e.preventDefault();
         var username=e.target.elements[0].value;
         var info=e.target.elements[1].value;
         //拼接地址
         var path=`/about/${username}/${info}`;
         //利用this.context.router.push()設(shè)置路由跳轉(zhuǎn)
         this.context.router.push(path);
     };
    
    • 注意:使用context必須設(shè)置contextTypes祠乃,否則梦重,拿到的this.context為空對象;
     //下載并prop-types模塊
     import PropTypes from "prop-types"
     //使用context必須設(shè)置contextTypes亮瓷,否則琴拧,拿到的為空對象;App為組件名嘱支;
     App.contextTypes={
         router:PropTypes.object
     };
    

setRouteLeaveHook

  • 離開組件的時候執(zhí)行的函數(shù)蚓胸;
    • 代碼:this.context.router.setRouteLeaveHook(this.props.route,this.LeaveHook)
    • 指的是在離開某個組件,跳轉(zhuǎn)到別的路由時除师,所調(diào)用的函數(shù)沛膳;
    • 在componentDidMount函數(shù)中使用該代碼,指的是在渲染頁面完成后汛聚,就設(shè)置setRouteLeaveHook锹安,當(dāng)離開時,就會執(zhí)行函數(shù)倚舀;
     import React,{Component} from "react";
     import PropTypes from "prop-types";
     class Contact extends Component{
         //當(dāng)渲染頁面完成后叹哭,執(zhí)行函數(shù)
         componentDidMount(){
             this.context.router.setRouteLeaveHook(this.props.route,this.LeaveHook);
         }
         LeaveHook=()=>{
             alert("離開該組件")
         };
         render(){
             return(
                 <div>
                     <h5>聯(lián)系我們</h5>
                     <button onClick={()=>{this.props.router.goBack()}}>go Back</button>
                 </div>
             )
         }
     }
     Contact.contextTypes={
         router:PropTypes.object
     };
     export default Contact;
    

簡書鏈接

react基礎(chǔ)知識快速學(xué)習(xí)
react學(xué)習(xí)大綱2-樣式和路由

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市痕貌,隨后出現(xiàn)的幾起案子风罩,更是在濱河造成了極大的恐慌,老刑警劉巖舵稠,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件超升,死亡現(xiàn)場離奇詭異,居然都是意外死亡哺徊,警方通過查閱死者的電腦和手機室琢,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來唉工,“玉大人研乒,你說我怎么就攤上這事汹忠×芟酰” “怎么了?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵宽菜,是天一觀的道長谣膳。 經(jīng)常有香客問我,道長铅乡,這世上最難降的妖魔是什么继谚? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮阵幸,結(jié)果婚禮上花履,老公的妹妹穿的比我還像新娘芽世。我一直安慰自己,他們只是感情好诡壁,可當(dāng)我...
    茶點故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布济瓢。 她就那樣靜靜地躺著,像睡著了一般妹卿。 火紅的嫁衣襯著肌膚如雪旺矾。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天夺克,我揣著相機與錄音箕宙,去河邊找鬼。 笑死铺纽,一個胖子當(dāng)著我的面吹牛柬帕,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播室囊,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼雕崩,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了融撞?” 一聲冷哼從身側(cè)響起盼铁,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎尝偎,沒想到半個月后饶火,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡致扯,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年肤寝,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片抖僵。...
    茶點故事閱讀 40,001評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡鲤看,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出耍群,到底是詐尸還是另有隱情义桂,我是刑警寧澤瞻赶,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布静尼,位于F島的核電站炼彪,受9級特大地震影響柠座,放射性物質(zhì)發(fā)生泄漏动知。R本人自食惡果不足惜息楔,卻給世界環(huán)境...
    茶點故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一万矾、第九天 我趴在偏房一處隱蔽的房頂上張望重绷。 院中可真熱鬧,春花似錦堰酿、人聲如沸疾宏。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽灾锯。三九已至,卻和暖如春嗅榕,著一層夾襖步出監(jiān)牢的瞬間顺饮,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工凌那, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留兼雄,地道東北人。 一個月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓帽蝶,卻偏偏與公主長得像赦肋,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子励稳,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,955評論 2 355

推薦閱讀更多精彩內(nèi)容