首页 > 代码库 > react-router传参

react-router传参

点击表单或按钮跳转

<form onSubmit={this.handleSubmit}>
  <input type="text" placeholder="userName"/>
  <input type="text" placeholder="repo"/>
  <button type="submit">Go</button>
</form>

第一种方法是使用browserHistory.push

import { browserHistory } from ‘react-router‘

// ...
  handleSubmit(event) {
    event.preventDefault()
    const userName = event.target.elements[0].value
    const repo = event.target.elements[1].value
    const path = `/repos/${userName}/${repo}`
    browserHistory.push(path)
  },

第二种方法是使用context对象

export default React.createClass({

  // ask for `router` from context
  contextTypes: {
    router: React.PropTypes.object
  },

  handleSubmit(event) {
    // ...
    this.context.router.push(path)   // 无参数
    this.context.router.push({pathname: path, state: {}})   // 有参数
  },
})

// 获取参数

componentDidMount() {
  this.setState({
     params: this.props.location.state.params
  })
}

 

react-router传参