Mar*_*zzo 5 reactjs react-router-dom
我有一个简单的应用程序,使用BrowserRouter'react-router-dom'v4.我试图location.pathname从<BrowserRouter/>组件内访问该属性,但无济于事:
class App extends Component{
render(){
return (
<BrowserRouter>
// How do I access this.props.location?
<div className={(this.props.location.pathnme === "/account") ? "bgnd-black" : "bgnd-white"} >
<Switch>
<Route path="/login" component={LoginPage}/>
<Route path="/success" component={LoginSuccess}/>
<Route path="/account" component={MyAccount}/>
...
<Route component={Error404}/>
</Switch>
</div>
</BrowserRouter>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过子组件访问应用程序的当前路径位置this.props.location.pathname,但我需要从父组件访问它,就在下面<BrowserRouter/>,运行与子组件无关的其他逻辑.我怎样才能获得这个位置?
您也可以使用withRouter具有类似结果的代码将代码放入render参数中,并避免使用"假" <Route/>.
基本上你把需要知道位置的JSX放在它自己的组件中,它被包装withRouter.这为组件提供了位置:
import { withRouter } from 'react-router-dom';
const Content = withRouter(props =>
<div className={(props.location.pathname === "/account") ? "backg...
...
</div>
);
Run Code Online (Sandbox Code Playgroud)
然后在主路由器部分中使用它:
class App extends Component{
render() {
return (
<BrowserRouter>
<Content/>
...
Run Code Online (Sandbox Code Playgroud)
由于react-router v5.1.0您可以使用useLocation.
https://reactrouter.com/web/api/Hooks/uselocation
class App extends Component{
render(){
const location = useLocation();
return (
<div className={(location.pathname === "/account") ? "bgnd-black" : "bgnd-white"} >
//...
</div>
);
}
}
// ...
<BrowserRouter>
<App />
</BrowserRouter>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6187 次 |
| 最近记录: |