反应路由器 v4 link onclick 得到 link 道具
react router v4 link onclick get link prop
我是 React Router v4 的新手。我有一个 link 在 onClick 事件中运行一个函数,然后重定向到一个特定的路由。
这是link:
<Link className={''}
to={'/test'}
onClick={this.testFunction}>To test</Link>
和测试函数:
testFunction(event){
e.preventDefault();
// do some things...
this.props.history.push('/test');
}
这可行,但我需要两次编写“/test”路由(在 Link 组件和函数中)。
有没有办法获得 "to" 道具,这样我就不必写两次了?
如果您在组件中使用 "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 官方文档
希望对您有所帮助!
我是 React Router v4 的新手。我有一个 link 在 onClick 事件中运行一个函数,然后重定向到一个特定的路由。
这是link:
<Link className={''}
to={'/test'}
onClick={this.testFunction}>To test</Link>
和测试函数:
testFunction(event){
e.preventDefault();
// do some things...
this.props.history.push('/test');
}
这可行,但我需要两次编写“/test”路由(在 Link 组件和函数中)。
有没有办法获得 "to" 道具,这样我就不必写两次了?
如果您在组件中使用 "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 官方文档
希望对您有所帮助!