关于react使用hashRouter父子组件中子组件点击按钮后路由跳转)
HashRouter基本代码
<HashRouter>
<Routers history={history}>
<Route exact path="/" component={Index}/>
<Route path="/father" component={Father}/>
</Routers>
</HashRouter>
class Router extends Component{
render(){
return(
{this.props.child}
)
}
}
父组件基本代码
class Father extends Component{
constructor(props){
super(props);
}
change(state){
this.props.history.push({pathname:'/',state:state})
}
render(){
return(
<div>
<Child onClick={this.change.bind(this)} />
</div>
)
}
}
子组件基本代码
class Child extends Component{
constrcutor(props){
super(props);
}
render(){
return(
<button onClick={()=>this.props.change({id:'111'})>click me</button>
)
}
}
所跳转到的路由所加载的组件获取所传参数(id)
在组件中使用this.props.location.state.id获取参数 或使用
console.log(this.props.location)
在浏览器的调试页面查看
结语
关于为什么不用官方推荐的browserRouter:
原因很简单,老大说要用的tomcat,而我试了很多方法配置没有成功,刷新页面就404。
关于没有用通配符传参:
其实是当时没想到,虽然做过子路由的demo,但是因为是刚入门react不久,东西用起来很生疏,完全靠自己摸索和问认识的用react做过项目的人,然后就掉进坑里了。
最后,其实很在工作上用到react还是很开心的,终于用到前后端分离的东西了。虽然总是在踩坑,但是从坑里出来的那份喜悦我就不多说了。