标签:rop extends pat end push dom imp 关于 click
安装
npm i react-router-dom -- save
<Router basename="/admin">
<Route path="/" exact component={()=>{<div>首页</div>}}>
<Route path="/about" exact component={()=>{<div>关于</div>}}>
</Router>
重定向组件
Redirect
import React from ‘react‘; import ‘./App.css‘; import { BrowserRouter as Router, Route, Link, Redirect } from ‘react-router-dom‘ function LoginInfo(props) { console.log(props) // 这是通过 state 传参 if(props.location.state.loginState === ‘success‘) { return ( <Redirect to="/admin"></Redirect> ) }else { return ( <Redirect to="/login"></Redirect> ) } } let login = ()=>{ let obj = { pathname:‘/logininfo‘, state:{ loginState:‘success‘ } } return ( <div> <Link to={obj} >登录</Link> </div> ) } class App extends React.Component{ render(){ return ( <Router> <Route path="/" exact component={()=>(<div>首页</div>)}></Route> <Route path="/login" exact component={()=>(<div> <Link to="/logininfo?loginState=‘success‘" >登录</Link> </div>)}></Route> <Route path="/login" exact component={login}></Route> <Route path="/logininfo" exact component={LoginInfo}></Route> </Router> ) } } export default App;
switch 内部的Route 只匹配一次
class App extends React.Component{ render(){ return ( <Router> <Switch> <Route path="/" exact component={()=>(<div>首页</div>)}></Route> <Route path="/login" exact component={()=>(<div> <Link to="/logininfo?loginState=‘success‘" >登录</Link> </div>)}></Route> <Route path="/login" exact component={login}></Route> <Route path="/logininfo" exact component={LoginInfo}></Route> <Route path="/abc" exact component={()=>(<div>首页1</div>)}></Route> <Route path="/abc" exact component={()=>(<div>首页2</div>)}></Route> </Switch> </Router> ) } }
不使用Link 按钮直接跳转
class ChildCom extends React.Component { render() { return ( <button onClick={this.show}> 点击回首页 </button> ) } show=()=>{ // console.log(this.props); this.props.history.push("/",{msg:‘给首页的数据‘}) } } class App extends React.Component{ render(){ return ( <Router> <Route path="/" exact component={(props)=>{console.log(props);return(<div>首页</div>)}}></Route> </Switch> </Router> ) } }
标签:rop extends pat end push dom imp 关于 click
原文地址:https://www.cnblogs.com/fanlinaweb/p/12786569.html