2017-07-16 60 views
1

我正在使用React构建单页Web应用程序。对于这个应用程序,我想阻止URL的更改,也避免使用href链接来防止“链接预览”出现在浏览器的左下角。使用反应路由器中的MemoryRouter导航JavaScript

为解决我的问题的前半部分,我发现使用反应路由器中的MemoryRouter可防止在应用程序内导航时URL更改。

下面是路由器的PoC:

import App from './stuff/main/App'; 
import {Route, MemoryRouter} from "react-router"; 
import default_page from "./stuff/pages/default_page" 
import another_page from "./stuff/pages/another_page" 

const app = document.getElementById('root'); 
ReactDOM.render(
    <MemoryRouter> 
     <App> 
     <Route exact path="/" component={default_page} /> 
     <Route path="/anotherpage" component={another_page} /> 
     </App> 
    </MemoryRouter>, 
    app 
); 
在应用

然后,我有这样的代码(工作):

... 
<Link to="/">default_page</Link> 
<Link to="/anotherpage">another_page</Link> 
{this.props.children} 
... 

我无法弄清楚如何使用改变页面的JavaScript MemoryRouter。我唯一可以找到的方法是使用链接标记,它使得URL显示在屏幕的左下角。如果我可以使用另一个元素并点击,我会是金色的。

回答

0

如果你是在<Route>子组件,你可以简单地做到这一点

<button onClick={()=>this.props.history.push('/anotherpage')} >another_page</button> 

如果你不是,你可以从HIGHT元委托该props.history

或者如果你在结构上很深,或者你只是不想委托历史对象,你可以创建一个没有paht的新的,所以它会匹配allways,它会授权你正确的历史对象。

<Route render={({history})=>(
    <button onClick={()=>history.push('/anotherpage')} >another_page</button> 
    // more buttons 
)} />