2017-07-03 46 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