react路由跳转传参方式

2019-11-01  本文已影响0人  any_5637

react在路由跳转进行传参有以下几种方式:
1. params方式传参
app.js

  import React from 'react';
  import { Router,Route, Redirect} from 'react-router';
  import { createBrowserHistory } from "history";

  import OnRefsTest from './component/OnRefs.js';
  import Test from './component/Test.js';
  const history = createBrowserHistory();

  export default class App extends React.Component {
  render() {
    return (
    <div className="App">
      <Router history={history}>
      <Redirect from='/' to='/one' /> 
      <Route path='/one' component={Test}></Route>
      <Route path='/user/:name' component={OnRefsTest}></Route>
      </Router>
    </div>
    );
  }
  }

子组件OnRefs.js

  import React    from 'react';
  import ReactDOM from 'react-dom';

  export default class OnRefsTest extends React.Component {
    onClick =() => {
      this.props.history.push("/one");
    }
    componentDidMount() {
      const { name } = this.props.match.params;
      console.log(name);
    }
    render() {
      return (
        <div>
          <button onClick={this.onClick}>我是返回</button>
          <input ref={node => { this.textInput = node }}></input>
        </div>
      )
    }
  }

组件Test.js

  import React    from 'react';
  import ReactDOM from 'react-dom';

  export default class Test extends React.Component {
    onClick= () => {
      this.props.history.push("/user/sam");
    }
    render() {
      return (
        <div>
          <span>我是路由</span>
          <button onClick={this.onClick}>加加加</button>
        </div>
      )
    }
  }

路由跳转:this.props.history.push("/user/:name");;
组件中在componentDidMount中接受参数:const { name } = this.props.match.params;
2. search方式传参
路由写法:

  // 路由
  <Route path='/user' component={OnRefsTest}></Route>

触发跳转:

  this.props.history.push({
    pathname: '/user',
    search: 'name=hehe&age=22'
  })

接受参数:

  componentDidMount() {
    console.log(this.props.location.search); // '?name=hehe&age=22'
  }

2. state方式传参
路由写法:

  // 路由
  <Route path='/user' component={OnRefsTest}></Route>

触发跳转:

      this.props.history.push({
      pathname: '/user',
      state: {
        name: 'hehe',
        age: 22
      }
    })

接受参数:

  componentDidMount() {
    console.log(this.props.location.state); //{name: "HEHE", age: 22}
  }
上一篇下一篇

猜你喜欢

热点阅读