【问题标题】:react router v4 link onclick get link prop反应路由器 v4 链接 onclick 获取链接道具
【发布时间】:2019-02-04 10:19:25
【问题描述】:

我是使用 react 路由器 v4 的新手。我有一个链接,它在 onClick 事件中运行一个函数,然后重定向到一个特定的路由。

这是链接:

<Link className={''} 
    to={'/test'}
    onClick={this.testFunction}>To test</Link>

以及测试功能:

testFunction(event){
    e.preventDefault();
    // do some things...
    this.props.history.push('/test');
}

这可行,但我需要编写两次“/test”路由(在链接组件和函数中)。

有没有办法获得“to”道具,这样我就不必写两次了?

【问题讨论】:

  • 在这种情况下为什么需要Link?如果你正在做this.props.history.push(),你可以切换到一个普通的&lt;a&gt;标签或带有onClick的w/e标签
  • 我以前从未尝试过这个,但我想你可以使用类似event.target.to
  • @Chimera.Zen 我想如果你使用 event.target.to 你会得到完整的路径,但路由器会使用相对路径
  • @HRK44 这是另一个不错的选择,我没有想到这个,我以为我只需要使用 react-router 组件
  • @Chimera.Zen 我尝试使用目标,我也得到了完整的路径,我的路由器也随之刹车。我想我可以解析它,但似乎更容易使用不同的解决方案。

标签: reactjs react-router-v4


【解决方案1】:

如果您在组件中使用“withRouter”:

import {Link, withRouter} from 'react-router-dom';
...    
export default withRouter(TestComponent);

您可以使用以下命令访问路由的路径:

this.props.match.path

在您的代码中使用它:

testFunction(event){
    e.preventDefault();
    // do some things...
    this.props.history.push(this.props.match.path);
}

当您在组件中使用“withRouter”时,您可以访问路线的匹配、位置和历史道具。

withRouter官方文档

match 官方文档

希望对你有帮助!

【讨论】:

  • 是的,我正在使用 withRouter,但没有尝试在匹配中查找信息,谢谢!
猜你喜欢
  • 2018-02-16
  • 2017-12-15
  • 2018-01-04
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
  • 1970-01-01
  • 2021-05-24
  • 1970-01-01
相关资源
最近更新 更多