欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

react-router JS 控制路由跳转实例

程序员文章站 2022-04-10 11:30:32
link组件用于正常的用户点击跳转,但是有时还需要表单跳转、点击按钮跳转等操作。这些情况怎么跟react router对接呢? 下面是一个表单。

link组件用于正常的用户点击跳转,但是有时还需要表单跳转、点击按钮跳转等操作。这些情况怎么跟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)
 },
})

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。