CodingNoob
#麻辣小龙虾#
采纳率60%
2019-01-18 11:03

react-router如何像vue-router通过this.$router.push的方式编程实现路由跳转

最近在研究react,遇到一个编程路由跳转问题,其实我就是想实现,如果像vue-router的方式通过this.$router.push({name: '', ''});类似的方式实现跳转到不同的组件,网上找了好多方法,都不行,不知道错在哪里,求大神指点一下。

我的版本:
图片说明
图片说明

import React, { Component } from 'react';
// import logo from './logo.svg';
import './App.css';
import './style/common/base.css';
import './style/common/reset.css';
import Index from './pages/index/index.jsx';
import List from './pages/list/List.jsx';
import Detail from './pages/detail/Detail.jsx';
import Form from './pages/form/form.jsx';
import { Route, HashRouter, Switch, withRouter } from 'react-router-dom';
class App extends Component {
  constructor (props) {
    super(props);
    this.state = {
      msg: {
        name: 'zhangan',
        age: '212',
        arr: [1, 2, 3, '21'],
        obj: {
          hight: '160cm',
          width: '89kg'
        }
      }
    }
    // this.routerUrl = this.routerUrl.bind(this);
  }
  childFun (state, val) {
    console.log('子组件往父组件传递的值!');
    console.log(state);
    console.log(val);
  }
  // 路由跳转,编程导航
  routerUrl (url, params) {
    this.props.history.push({
      pathname:"/index",
      query:{
        name:"inbox",
        myas:"哈哈"
      }
    });
  }
  render() {
    return (
      <div className="App">
        <div className="router">
          <button onClick={this.routerUrl.bind(this)}>index</button>
          <button onClick={this.routerUrl.bind(this)}>detail</button>
          <button onClick={this.routerUrl.bind(this)}>list</button>
          <button onClick={this.routerUrl.bind(this)}>form</button>
        </div>
        <div className="content">
        <HashRouter>
          <Switch>
              <Route exact path="/" component={Index}/>
              <Route exact path="/list" component={List}/>
              <Route exact path="/detail" component={Detail}/>
              <Route exact path="/form" component={Form}/>
          </Switch>
        </HashRouter>

          {/* <Index />
          <Detail />
          <List />
          <Form msg={this.state.msg} clickFun={this.childFun.bind(this)}/> */}
        </div>
      </div>
    );
  }
  componentWillMount () {
    console.log(this);
  }
}
export default App;

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

相关推荐