![](/img/trans.png)
[英]Easier way to dynamically render components with sidebar navigation using react router
[英]React Router - Is there an 'easier' way to route to a new path besides using Context?
是否有一種更簡單或更新的方法,例如單擊一個按鈕,然后單擊該按鈕的onClick,重新路由到新路徑?
.... BESIDES在組件上使用上下文方法?
謝謝
有幾種方法:
1. withRouter-來自react-router(高階組件)的HoC ,它包裝了另一個組件以提供props.router
import { withRouter } from 'react-router';
class App extends Component {
...
onClickButton(){
this.props.router.push('/path')
}
...
}
export default withRouter(App);
2. 歷史單例 (hashHistory / browserHistory)
import { hashHistory} from 'react-router';
class App extends Component {
...
onClickButton(){
hashHistory.push('/path')
}
...
}
3.也可以從組件中的道具獲取歷史記錄 ,這將傳遞給路線
....
<Route path="/" component={App} />
然后在組件
class App extends Component {
...
onClickButton(){
this.props.history.push('/path')
}
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.