Cor*_*rey 6 html javascript css reactjs react-router-v4
我正在使用 React 构建一个单页 Web 应用程序。对于这个应用程序,我想防止 URL 更改,并避免使用 href 链接来防止“链接预览”显示在浏览器的左下角。
为了解决我的前半部分问题,我发现使用 react-router 中的 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
);
Run Code Online (Sandbox Code Playgroud)
然后在应用程序中我有这样的代码(有效):
...
<Link to="/">default_page</Link>
<Link to="/anotherpage">another_page</Link>
{this.props.children}
...
Run Code Online (Sandbox Code Playgroud)
我不知道如何使用 MemoryRouter 在 javascript 中更改页面。我能找到的唯一有效方法是使用 Link 标记,这会导致 url 显示在屏幕的左下角。如果我可以使用另一个元素和 onclick,我会很高兴。
如果您位于 的子组件中<Route>,则应该有历史记录可用:
<button onClick={()=>this.props.history.push('/anotherpage')} >another_page</button>
Run Code Online (Sandbox Code Playgroud)
如果不是,您可以props.history从父元素传递。
或者如果你对结构有深入了解,你应该使用withRouterHOC
或者您可以创建一个不带pathprop 的新对象,因此它将始终匹配并为您提供正确的历史对象。
<Route render={({history})=>(
<button onClick={()=>history.push('/anotherpage')} >another_page</button>
// more buttons
)} />
Run Code Online (Sandbox Code Playgroud)