2017-07-03 45 views
3

我有反應路由器-DOM這個路徑:如何通過反應路由器v4中的按鈕單擊在路徑上導航?

<BrowserRouter> 
    <div> 
    <Route exact path='/(index.html)?' component={Home}/> {/* app = home */} 
    <Route path='/register' component={Registration}/> 
    </div> 
</BrowserRouter> 

一切正常,現在在我的部件在任何地方我想的onClick改變路徑,這樣的代碼:

<button onClick={() => history.push('/the/path') }> change path </button> 

我怎樣才能做到這一點?

回答

2
import {withRouter} from 'react-router-dom'; 
... 

class App extends React.Component { 
    ... 

    nextPath(path) { 
    this.props.history.push(path); 
    } 

    render() { 
    return (
     <button onClick={() => this.nextPath('/the/path') }> 
     change path 
     </button> 
    ); 
    } 
} 

export default withRouter(App); 
+0

請問您能告訴我什麼是'withRouter'嗎? –

+0

@PardeepJain https://reacttraining.com/react-router/web/api/withRouter – soywod