Viv*_*osh 5 reactjs react-router
我想访问当前位置路径(如/ home),而不使用某些比较逻辑的历史记录键.
如何从反应路由器2中的hashHistory访问它.
另外,我如何访问上一个路径?
小智 6
您可以从location路径组件的prop 获取当前路径名.
从Route组件的this.props.location访问位置.如果你想在树中深入了解它,你可以使用你的应用程序用于获取高低的道具的任何约定.一种选择是自己提供上下文:
// v2.0.x const RouteComponent = React.createClass({
childContextTypes:{location:React.PropTypes.object},getChildContext(){return {location:this.props.location}}})
看看这里.
要获得当前路径,您可以使用location.pathname.
访问路径的一种方法是通过this.props.location反应组件。
import React from 'react'
import { render } from 'react-dom'
import { browserHistory, Router, Route, Link } from 'react-router'
class Child extends React.Component {
render() {
let location = this.props.location
return (
<div>
<h1>Child Component</h1>
<p>{location.pathname}</p>
</div>
)
}
}
class App extends React.Component {
render() {
return (
<div>
{this.props.children}
</div>
)
}
}
render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="child" component={Child} />
</Route>
</Router>
), document.getElementById('example'))
Run Code Online (Sandbox Code Playgroud)
如果您想通过历史记录收听当前位置的变化,另一种方式 -
import { createHistory } from 'history'
let history = createHistory()
// Listen for changes to the current location. The
// listener is called once immediately.
let unlisten = history.listen(function (location) {
console.log(location.pathname)
})
// When you're finished, stop the listener.
unlisten()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19084 次 |
| 最近记录: |