react-router @4用法整理
router@4react-router@4官方文档 这篇文章主要介绍了react-router@4的基本用法,包括动态路由,编程式导航等
import { Switch,BrowserRouter as Router,Route,Redirect} from 'react-router-dom'; class SwitchCom extends Component { render() { return ( <Router> <Switch> <Route path="/cart" component={Cart}></Route> <Route path="/search" component={Search} /> <Route path="/home" component={Main} /> <Redirect from="/" to="/home"></Redirect> <Route path="/mine" component={Mine}></Route> <Route path="/class" component={Class}></Route> <Route component={NoMatch}></Route> </Switch> </Router> ) } }
3.动态路由的基本用法: import { BrowserRouter as Router,NavLink} from 'react-router-dom'; <div className="tab-bar"> <Route path="/index" exact component={Index}></Route> <Route path="/index/news" component={News}></Route> <Route path="/index/course" component={Course}></Route> <Route path="/index/mine" component={Mine}></Route> <ul className="footer"> <li><NavLink exact to="/index" activeStyle={{ color: '#4dc060' }}>首页列表项目 </NavLink></li> <li><NavLink to="/index/news" activeStyle={{ color: '#4dc060' }}>资讯</NavLink></li> <li><NavLink to="/index/course" activeStyle={{ color: '#4dc060' }}>课程</NavLink></li> <li><NavLink to="/index/mine" activeClassName="selected">我的</NavLink></li> </ul> </div>
关于NavLink 和 Link: 4.编程式导航(withRouter用法) import {withRouter} from 'react-router-dom'; goBack(){ this.props.history.goBack(); } goDetail(){ this.props.history.push('/detail'); } goDetailWithParam(item){ this.props.history.push({pathname : '/cart',state:{item}}); } <span className="ico" onClick={this.goBack.bind(this)}> <i className="iconfont"></i> </span> //这里的item来自for循环的每一项 <li onClick={this.goDetailWithParam.bind(this,item)} key={encodeURI(item.imgUrl)}> export default withRouter(Header);
5 总结: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |