路由
ReactRouter三大组件:
Router:所有路由组件的根组件(底层组件),包括路由规则的最外层容器,可以再一个组件写多个
Route:路由规则匹配组件,显示当前规则对应的组件
Link:路由跳转的组件,to属性可以传路径也可以传对象;replace属性点击链接后,直接替换成历史访问记录的原地址
动态路由:
function Product(props) {
return (
<div>
<h1>产品页面,产品ID:{props.match.params.id}</h1>
</div>
)
}
<Link to="/product/123">Product</Link>
<Route path="/product/:id" component={Product}></Route>
全部代码:
import React from 'react';
// history模式/后端匹配使用
import {BrowserRouter as Router,Link,Route} from 'react-router-dom';
function Home() {
return (
<div>
<h1>首页</h1>
</div>
)
}
function Me(props) {
console.log(props)
return (
<div>
<h1>个人中心</h1>
</div>
)
}
function Product(props) {
return (
<div>
<h1>产品页面,产品ID:{props.match.params.id}</h1>
</div>
)
}
class App extends React.Component {
render() {
let meObj = {pathname: "/me", search: "?username=admin", hash: "#abc", state: {msg: "hello"}}
return (
<div id="app">
<Router basename="/admin">
<div className="nav">
<Link to="/">Home</Link>
<Link to="/product/123">Product</Link>
<Link to={meObj} replace>个人中心</Link>
</div>
<Route path="/" exact component={Home}></Route>
<Route path="/product/:id" component={Product}></Route>
<Route path="/me" component={Me}></Route>
</Router>
</div>
)
}
}
export default App;
路由重定向
访问某个组件时,如果有重定向组件,那么就会修改页面的路径,使得页面内容显示为所定向路径的内容
Switch组件
可以使Switch组件内容的route只匹配到一个(多个重复),只要匹配到了,剩余的路由规则将不再匹配
import React from 'react';
import {BrowserRouter as Router,Link,Route,Redirect,Switch} from 'react-router-dom';
function LoginInfo(props) {
if (props.location.state.loginState === 'success') {
// 重定向 用的比较少 可以自己设置跳转的页面
return <Redirect to='/'></Redirect>
} else {
return <Redirect to='/login'></Redirect>
}
}
let FormCom = ()=>{
let pathObj = {pathname: '/logininfo', state: {loginState: 'success'}}
let pathObj2 = {pathname: '/logininfo', state: {loginState: 'fail'}}
return (
<div>
<h1>表单验证</h1>
<Link to={pathObj}>登录验证后的页面1</Link>
<Link to={pathObj2}>登录验证后的页面2</Link>
</div>
)
}
// 不用Link实现跳转
class ChildCom extends React.Component {
render() {
return (
<div>
<button onClick={this.clickEvent}>跳转到首页</button>
</div>
)
}
clickEvent = () => {
// this.props.history.go(1) 前进 等的方法
this.props.history.push("/",{msg: "这是由ChildCom组件发给首页的数据"})
}
}
class App extends React.Component {
render() {
return (
<div>
<Router>
<Switch>
<Route path='/' exact component={(props)=>{console.log(props);return (<h1>首页</h1>)}}></Route>
<Route path='/form' exact component={FormCom}></Route>
<Route path='/login' exact component={()=>(<h1>登录页</h1>)}></Route>
<Route path='/logininfo' exact component={LoginInfo}></Route>
<Route path='/123' exact component={()=>(<h1>1</h1>)}></Route>
<Route path='/123' exact component={()=>(<h1>2</h1>)}></Route>
<Route path='/child' exact component={ChildCom}></Route>
</Switch>
</Router>
</div>
)
}
}
export default App;