百度直接搜react路由的資料比較少号胚,建議直接上github街立,頭部就是docs鏈接了
文檔雖然是英文的啸盏,但是很清楚骨田,就算用谷歌直接翻譯都很清晰(因為主要是代碼耿导,沒啥文字)
docs : https://reacttraining.com/react-router/web/example/url-params
路由
安裝完腳手架,在*App.js*
稍作修改
引入路由
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
修改<App />
<Router>
<div>
<h2>這是react-router渲染出來的</h2>
<Route path="/:id" component={Child}/>
</div>
</Router>
可以看出來态贤,router竟然是組件格式舱呻,很棒的設(shè)計。
添加頁面
Child
const Child = ({ match }) => (
<div>
<h3>ID: {match.params.id}</h3>
</div>
)
組件component 竟然是函數(shù)
ok,看效果
關(guān)于路由的精確定位問題
比如 我要訪問 / 但是如果直接寫
<Route path="/" component={Home} />
訪問 / 的時候是沒有問題的箱吕,但是訪問二級(以及更高)的路由芥驳,會發(fā)現(xiàn),多了Home的渲染茬高。比如訪問 My
home頁面也出來了兆旬,這時候給 / 添加 exact 就可以了
<Route exact path="/" component={Home} />
頁面導(dǎo)入
Code
import React from 'react'
var title = 'Home Page'
export default class Repos extends React.Component {
render() {
return (
<div>
<h1>{title}</h1>
</div>
)
}
}
大概這個格式,引入
import Home from './home'
然后就給component了
<Route exact path="/" component={Home} />
NavLink 轉(zhuǎn)跳
一般都是用 Link,使用方法一樣怎栽,引入就可以用了
不過NavLink更靈活(顧名思義丽猬,在Nav中使用),就介紹它
先引入
import { NavLink } from 'react-router-dom'
然后使用熏瞄,Code
import { NavLink } from 'react-router-dom'
var activeNavStyle = {
color: 'red'
}
var FootComponent = React.createClass({
render: function() {
return (
<div>
<NavLink to="/" exact activeStyle={activeNavStyle}>首頁</NavLink>
<NavLink to="/my" activeStyle={activeNavStyle}>我的</NavLink>
</div>
)
}
})
activeStyle
是處于當前路由的時候展示的樣式宝鼓,還有一個Api是 activeClassName
這里用了 exact
是為了精確匹配當前的位置
除了exact
還有strict
他是在精確匹配,并且后面還有 /
的時候才被執(zhí)行
還有一個isActive
的API巴刻,當路由被激活的時候愚铡,會執(zhí)行這個函數(shù)
isActive = { (match, location)={console.log('勞資被激活了')} }
<br />
組件
創(chuàng)建組件
var component = React.createClass({
render: function() {
return <h1>come on!</h1>
}
})
使用
不需要像vue 或者 angular 一樣需要在聲明胡陪,只要在同一個作用域下(同一個js文件下)沥寥,直接導(dǎo)入
<!-- 后面記得加標簽結(jié)束標記 / -->
<component />
創(chuàng)建Js組件
NavLink 為例子(下面的二大金剛)
import React, { Component } from 'react'
import {
BrowserRouter as Router,
Route
} from 'react-router-dom'
import { NavLink } from 'react-router-dom'
var activeNavStyle = {
color: 'red'
}
class Foot extends Component {
render() {
return (
<div>
<NavLink to="/" exact activeStyle={activeNavStyle}>首頁</NavLink>
<NavLink to="/my" activeStyle={activeNavStyle}>我的</NavLink>
</div>
)
}
}
export default Foot;
導(dǎo)入
import Foot from './components/foot'
效果(修改了下樣式,可能跟上面的代碼不大一樣)
Tips: JSX里面 class的寫法是 calssName
<div className="foot"></div>
注釋的話是
{/**/}
OK ,好了柠座。
參考鏈接: https://reacttraining.com/react-router/web/api/NavLink/activeClassName-string
--end--