上次用react-router 的时候 还是3.x 很久不用 已经到react-router5.x 了
废话不多说 上代码
配置
react: ^16.8.6,
react-dom: ^16.8.6,
react-router: ^5.0.0,
react-router-dom: ^5.0.0,
路由配置
用HashRouter还是BrowserRouter 自己来定(优先BrowserRouter ) 两者区别 两种路由的区别
import { HashRouter,BrowserRouter, Route, Link, Switch } from "react-router-dom";
....
//用HashRouter还是BrowserRouter 自己来定
<BrowserRouter>
<Link to="/a" style={{color:'black'}}>
<div>点击跳转到a</div>
</Link>
<Link to="/b" style={{color:'black'}}>
<div>点击跳转到b</div>
</Link>
<Switch>
<Route exact path='/' component={App1}/>
<Route path='/a' component={App1}/>
<Route path='/b' component={App2}/>
<Switch/>
</BrowserRouter>
....
image.gif
路由组件 js路由跳转
//路由组件 js路由跳转
constructor(props){
super(props);
}
//有history记录跳转
this.props.history.push('/register');
//无history记录跳转
this.props.history.replace('/register');
//返回
this.props.history.goBack();
image.gif
一般组件withRouer js路由跳转
import { withRouter} from "react-router-dom";
class Demo extends React.PureComponent {
...
//暴露时加了高阶组件withRouer ,这样一般组件内部才能操作this.props.history
demo1=()=>{
this.props.history.push('/**');
}
}
//withRouer高阶组件 必须
export default withRouter(Demo);
image.gif