React,Link路由的跳转和传参
1. 安装react-router-dom
npm install react-router-dom
2. 在项目中使用react-router-dom
import { BrowserRouter as Router} from 'react-router-dom'
ReactDOM.render(<Router><App /></Router>, document.getElementById('root'));
3. 接下来在组件中就可以使用路由跳转了
- 在需要使用路由跳转的页面引入下面几个常用组件(可根据需要引入)
import {Route, NavLink, Switch, Redirect} from 'react-router-dom'
- 定义几个点击跳转的按钮,
<NavLink>
自带有active
的class类名
<NavLink to="/one">页面1</NavLink>
<NavLink to="/two">页面2</NavLink>
<NavLink to="/three">页面3</NavLink>
<NavLink to="/four">页面4</NavLink>
<Switch>
<Route path="/one" component={One}/>
<Route path="/two" component={Two}/>
<Route path="/three" component={Three}/>
<Route path="/four" component={Four}/>
<Redirect from="/" to="/one" exact/>
<Route component={NotFound}/>
</Switch>
<NavLink to="/two/a">子路由a</NavLink>
<NavLink to="/two/b">子路由b</NavLink>
<Switch>
<Route path="/two/a" component={TwoA}></Route>
<Route path="/two/b" component={TwoB}></Route>
<Redirect from="/two" to="/two/a" exact></Redirect>
</Switch>
4.传递参数
<Route path='/path/:name' component={Path}/>
<NavLink to="/path/2">跳转传参</NavLink>
this.props.history.push({pathname:"/path/" + name});
读取参数用:this.props.match.params.name
<Route path='/query' component={Query}/>
<NavLink to={{ path :'/query', query:{name:'sunny'}}}>跳转传参</NavLink>
this.props.history.push({pathname:"/query",query:{name:'sunny'}});
读取参数用: this.props.location.query.name
<Route path='/sort' component={Sort}/>
<NavLink to={{path:'/sort ', state:{name :'sunny' }}}>跳转传参</NavLink>
this.props.history.push({pathname:"/sort ",state:{name:'sunny'}});
读取参数用: this.props.location.query.state
<Route path='/web/departManange ' component={DepartManange}/>
<NavLink to="web/departManange?tenantId=12121212">跳转传参</NavLink>
this.props.history.push({pathname:"/web/departManange?tenantId" + row.tenantId});
读取参数用: this.props.location.search
注意 query state 和 search 传递的参数刷新页面后参数丢失!
最后 逆战 小白变大白!!!