React router的Route应用
Route 是 React Router中用于配置路由信息的组件,每当有一个组件需要根据 URL 决定是否渲染时,就需要创建一个 Route。 react-router 中的很多特性都与 React 保持了一致,比如它的声明式组件、组件嵌套,当然也包括 React 的状态机特性。 1.path 每个Route都需要一个path属性,path属性是一个url,当URL匹配一个Route时,这个Route中定义的组件就会被渲染出来。 ? 2.Route渲染组间的方式 (1)Component component的值是一个组件,当URL和Route匹配时,Component属性定义的组件就会被渲染。 <Route path="/mycom" component={MyCom} > (2)Render Render 值是一个函数,这个函数返回一个React元素。这种方式方便地为待渲染的组件传递额外的属性。 <Route path=‘/mycom’ render={(props) => { <MyCom {…props} data={extraProps} /> //MyCom 组件接收了一个额外的data属性 }}> </Route> (3)children Children的值也是一个函数,函数返回要渲染的React元素。与前面不同是,无论是否匹配成功,children返回的组件都会被渲染。匹配不成功时,match属性为null。 <Route path="/myCom" render={(props) => { <div className={props.match ? ‘active‘ : ‘‘}> <Foo {…props} data={extraProps} /> </div> }} </Route> 如果Route匹配当前URL,待渲染元素的根节点div的class将设置成active. ? 3.多级路由 在路由里面继续写路由,挂载组件,就可以实现多级路由。路由嵌套实现。 <Route path=‘/myCom’ component={myCom}>
<Route path=‘/myCom/sonCom’ component={SonCom}></Route>
</Route>
如果多级路由嵌套的层次太深,那我们写子路由的path就会特别麻烦,所以可以这样: <Route path=‘/mycom’ render={(props) => {
<Route path={`${props.match.path}/sonCom`} component={SonCom} /> }}>
</Route>
Match是从props解构出来,match.path就是我们当前这个路由的路径,这样不管嵌套多深,都可以写上一级的路由 ? 4.动态传参 /foodlist/:id,传过去的值就在路由挂载组件的props中,props里有个match,match中有个params,?注意:props只在路由挂载的组件才有 <Route path=‘/foodlist/:id’ component={MyCom} /> MyCom 组件的props中就可以获取到id 可以在一个组件中用 this.props.history.push(“/path”,{name: “hellow”}),来进行传参,传过去的值在props.location.state中 ? 5.withRouter 一个典型的高阶组件,如果我们既想实现点击跳转,又不想用Link的a标签,我们可以用withRouter给我们吐出来一个实现点击跳转路由的组件。 Eg. import { withRouter } from ‘react-router-dom’; //使用自定义的组件: <CustomNavLink to="/food">food</CustomNavLink> <CustomNavLink to="/wiki">wiki</CustomNavLink> <CustomNavLink to="/profile">profile</CustomNavLink> //给自定义组件实现点击功能: const CustomNavLink = withRouter(class EnhenceCustomNavLink extends Component { render () { return ( <li onClick={this.goto.bind(this)}> { this.props.location.pathname === this.props.to ? ‘>‘ + this.props.children : this.props.children } </li> ) } goto () { this.props.history.push(this.props.to) } })
假如你的组件没有路由信息,你可以使用withRouter(component)将这个组件包起来,props里面就有路由信息了。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |