一:导入及基础用法
react router包含三类组件:路由组件,路由匹配组件,导航组件
import { BrowerRouter,Route,Link } from “react-router-dom”
路由组件
分两种:browser和HashRouter,服务器响应请求用BrowserRouter,静态文件响应用HashRouter(一般都是BrowserRouter)
路由器配组件
分两种:Route和Switch
Route用来写具体说到每一个路由的跳转,Switch用来把多个Route组合到一起。可以不放在一起,放在一起Switch将会迭代其所有元素,并且仅渲染当前路径匹配的第一个元素。
理解:
代码是这样的:

如果路径是localhost:3000/#/about/contact,那么Home,About,Contact都会渲染,
如果代码加上<Switch>

<Switch>
  <Route path="/" component={Home} />
  <Route path="/about" component={About} />
  <Route path="/contact" component={Contact} />
</Switch>

同样的路径只会渲染{Home}(其第一个,如果把放在第一个就会渲染About,如果想要无视书写顺序直接只匹配到Contact不匹配前面的可以在里面加上exact,即这样如果路径是:localhost:3000/#/contact,就只会匹配到Contact,不匹配Home了。
关于<Route>:
<Route>有三种属性:children,component和render,children不常用。
component和render都可以用于渲染组件,区别在于如果单纯只为了渲染组件,不传递或者改变其状态的话,用component,如果要在挂载的时候就传递参数的话用render。
eg:

<Route path="/componentUser/:id" component={ComponentUser}/>
   <Route path="/renderUser/:id" render={
({match}) => (<RenderUser key={match.params.id} userId={match.params.id}/>)  }/>

导航组件
用法:<Link to="/">Home</Link>
link中写了在这里要跳转的地址,router中写这个地址具体加载那个组件。
Link to="/"是页面最上面导航栏中会写入的路径,在router中会比对,当router中的path与导航栏中的路径一样的话,加载对应的组件。
二,API
1,

import { BrowserRouter } from 'react-router-dom'

	<BrowserRouter
  	basename={optionalString}
  	forceRefresh={optionalBool}
  	getUserConfirmation={optionalFunc}
  	keyLength={optionalNumber}
	>
	  <App/>
	</BrowserRouter>

basename:String,当前位置的基础URL与服务器有关。
getUserConfirmation: func,当导航需要确认时执行的函数。
forceRefresh:bool 当导航设置为true时,导航过程中会刷新页面。
keyLength:number,location.key的长度。默认是6
这一部分用到的概率不大。
2,<HashRouter>
使用基本上与<BrowserRouter>一样,区别仅在于服务器响应和静态页面响应。
3,<Link>

<Link to="/courses" replace />

to:后面加需要跳转的路径或地址
replace:bool当设置为true时无论点多少次都只会有一个历史记录。可不加,不加为默认的
false
4,<NavLink>
如果想要给link加样式的话可以用这个。
<NavLink>这个会渲染成一个a标签。
activeClassName:string。这个用来给渲染成的a标签加class引入外部样式。
activeStyle:object。

<NavLink
  			to="/faq"
  			activeStyle={{
    			fontWeight: 'bold',
   			color: 'red'
   			}}
		     >FAQs</NavLink>

这样用于类似直接在添加行内样式,可以直接写在html中。
exact:bool,与router中的exact一样,只有地址完全匹配时上面两个才能用。
isActive: func,用于添加链接的额外功能,比如弹出弹框等。
5,<Prompt>
当用户离开当前页面时出现提示。

import { Prompt } from 'react-router'

	<Prompt
  	 when={formIsHalfFilledOut}
  	 message="Are you sure you want to leave?"
	/>

message:string.当离开时提示的信息。

message:fuc.离开时调用的函数。
eg:

when:bool,弹出这个弹框的条件。
6,< Redirect >
类似路由重定向,<Redirect to="/somewhere/else"/>,清除掉原来这个路径指向的地址改成to后面指向的地址。
to:目标地址。
push:bool, 默认为false,当为true时,把新地址加在访问记录里,也就是会有两个记录。
from:string,需要被重定向的地址。

7,<Route>
只要地址和路由匹配的话组件就会渲染。
react渲染的方法有三种,component,child,render。
component:路由会创建一个新的组件重新挂载。

<Route path="/user/:username" component={User}/>

	const User = ({ match }) => {
	  return <h1>Hello {match.params.username}!</h1>
	}

render:可以用于内联渲染和包装组件,总之如果有传递参数就可以选择用render

// 便捷的行内渲染
	<Route path="/home" render={() => <div>Home</div>}/>

	// 包装/合成
	const FadingRoute = ({ component: Component, ...rest }) => (
	  <Route {...rest} render={props => (
	    <FadeIn>
	      <Component {...props}/>
	    </FadeIn>
	  )}/>
	)
	
	<FadingRoute path="/cool" component={Something}/>

children:不管地址是否匹配都会渲染的内容。

<ul>
	  <ListItemLink to="/somewhere"/>
	  <ListItemLink to="/somewhere-else"/>
	</ul>

	const ListItemLink = ({ to, ...rest }) => (
	  <Route path={to} children={({ match }) => (
	    <li className={match ? 'active' : ''}>
	      <Link to={to} {...rest}/>
	    </li>
	  )}/>
	)

path:string,匹配的url
exact:bool,当为true时路径与页面地址必须完全一致。
strict:bool,强制路径结尾必须有“/”才能匹配。
PS:强制没有“/"::strict和exect都必须为true.

<Route exact strict path="/one" component={About}/>

sensititive:bool,为true时区分大小写。
8,history对象
history对象是可变的,因此可以从prop里来获取location而不是history.lqoaction。参照如下:

class Comp extends React.Component {
  	componentWillReceiveProps(nextProps) {
    	// locationChanged 变量为 true
    	const locationChanged = nextProps.location !== this.props.location

    	// 不正确,locationChanged 变量会 *永远* 为 false ,因为 history 是可变的(mutable)。
    	const locationChanged = nextProps.history.location !== this.props.history.location
  	}
     }
	<Route component={Comp}/>

9,location对象
当前位置,在react中用如下方式来获取location:
在 Route component 中,以 this.props.location 的方式获取,
在 Route render 中,以 ({ location }) => () 的方式获取,
在 Route children 中,以 ({ location }) => () 的方式获取,
在 withRouter 中,以 this.props.location 的方式获取。
/ 通常你只需要这样使用 location

// 但是你同样可以这么用
const location = {
  pathname: '/somewhere'
  state: { fromDashboard: true }
}

<Link to={location}/>
<Redirect to={location}/>
history.push(location)
history.replace(location)

10,match对象
match对象包含了与URL匹配的信息。
参数有path,isExact,parpams,url等,可以用以下方法调用。
在 Route component 中,以 this.props.match 方式。
在 Route render 中,以 ({ match }) => () 方式。
在 Route children 中,以 ({ match }) => () 方式
在 withRouter 中,以 this.props.match 方式
matchPath 的返回值 当一个 Route 没有 path 时,它会匹配一切路径,你会匹配到最近的父级。在 withRouter 里也是一样的。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐