在onClick函数中传递路由器路径

时间:2017-02-06 18:13:13

标签: javascript html reactjs url-routing

我有一个React表单,其中包含以下表单提交按钮:

<Link 
    className="btn btn-secondary btn-width-200 search-submit" 
    to={{pathname: '/booking/search', query: this.state.filters}}>
     Search

</Link>

在上面的link中,我想在按钮点击时调用函数handleSubmit(evt)

handleSubmit(evt) {
    evt.preventDefault();
    this.setState({form_submitted: true});
}

<Link className="btn btn-secondary btn-width-200 search-submit" to={{pathname: '/booking/search', query: this.state.filters}} onClick={this.handleSubmit.bind(this)}>Search</Link>

但是以下忽略了to={{pathname: '/booking/search', query: this.state.filters}},只考虑了handleSubmit函数

是否要将to={{pathname: '/booking/search', query: this.state.filters}}添加到handleSubmit功能?或者无论如何要解决这个问题?

3 个答案:

答案 0 :(得分:2)

您需要了解的是,如何使用react-router API实现路由。基本上,您可以在两个API browserHistoryhashHistory上配置它。 (link

因此,换句话说,通过调用browserHistory.push('/booking/search')hashHistory.push('/booking/search'),您应该能够在路线之间导航。

还有可用的redux版本,以防万一你想通过某些动作调度管理你的导航(虽然没有必要)。 Link

了解更多信息:Programmatically navigate using react router

答案 1 :(得分:1)

您可以在外部函数中使用推送路由器方法,而不是使用Link。例如:

redirectFunction() {
 this.handleSubmit()
 router.push({
  to: '/booking/search',
  query: this.state.filters
 })
}

render () {
  <div 
   className="btn btn-secondary btn-width-200 search-submit" 
   onClick={this.redirectFunction.bind(this)}>
     Search 
  </div>
}

答案 2 :(得分:1)

这:

import {Link} from 'react-router';

handleSubmit(evt) {
    evt.preventDefault();
    this.setState({form_submitted: true});
}

<Link 
    className="btn btn-secondary btn-width-200 search-submit" 
    to={{pathname: '/booking/search', query: this.state.filters}}>
     Search

</Link>

可以替换为:

import {browserHistory} from 'react-router';

handleSubmit(evt) {
    evt.preventDefault();
    this.setState({form_submitted: true});
    return this.redirect('/booking/search', this.state.filters);

}

redirect(to, query) {
   browserHistory.push({pathname: to, query})

}

<a
    className="btn btn-secondary btn-width-200 search-submit" 
   onClick={this.handleSubmit} >
     Search

</a>