[英]React router anchor link
I use react for some component and I have a navigation menu outside the react root.我对某些组件使用了 react,并且在 react 根目录外有一个导航菜单。
I want to change react component inside the root when I click to menu links.当我单击菜单链接时,我想更改根内的反应组件。
I search and see react-router
is a solution but I don't know how to do this.我搜索并看到
react-router
是一个解决方案,但我不知道该怎么做。
Also note I don't want to use Hash urls.另请注意,我不想使用哈希网址。
Here is example of my codes这是我的代码示例
<div class="menu">
<a href="page2">page 2</a>
</div>
<div class="react-root"></div>
And I call react render for react-root
div only.我只为
react-root
div 调用 react 渲染。
How can I tell react to change the component when I click on page 2?当我点击第 2 页时,如何告诉 React 更改组件? Is react-router is good solution and how Can I do it with react router?
react-router 是一个很好的解决方案,我如何使用 react router 做到这一点?
The point of using react-router
is generally to have page not refreshed as user navigates.使用
react-router
目的通常是在用户导航时不刷新页面。 If you bring your nav links inside the react app you will get to experience single page application without refreshing the page.如果您将导航链接带入 React 应用程序,您将无需刷新页面即可体验单页应用程序。
Otherwise, you can have something like this:否则,你可以有这样的事情:
import React from "react";
import ReactDOM from "react-dom";
import { Route, BrowserRouter as Router } from "react-router-dom";
const App = () => <div>Home Page</div>;
const App2 = () => <div>Page 2</div>;
const routing = (
<Router>
<div>
<Route exact path="/" component={App} />
<Route path="/page2" component={App2} />
</div>
</Router>
);
ReactDOM.render(routing, document.getElementById("react-root"));
But better way is something like this:但更好的方法是这样的:
const App = () => <div>Home Page</div>;
const App2 = () => <div>I am Page 2</div>;
const routing = (
<Router>
<div class="menu">
<Link to="/">Home Page</Link>
<Link to="/page2">Page 2</Link>
</div>
<div>
<Route exact path="/" component={App} />
<Route path="/page2" component={App2} />
<Route path="/page3" component={App} />
</div>
</Router>
);
ReactDOM.render(routing, document.getElementById("react-root"));
Here is the code sandbox link where you can see the difference between two https://codesandbox.io/s/holy-wind-olex5?fontsize=14&hidenavigation=1&theme=dark这是代码沙箱链接,您可以在其中查看两个https://codesandbox.io/s/holy-wind-olex5?fontsize=14&hidenavigation=1&theme=dark之间的区别
I solved it by getting helps from this question How to get history on react-router v4?我通过从这个问题中获得帮助解决了这个问题How to get history on react-router v4?
Here is my code这是我的代码
document.getElementById("test").onclick = function(e){
e.preventDefault();
history.push("/page2")
}
and it's working!它正在工作!
https://codesandbox.io/s/inspiring-goldberg-utryd?fontsize=14&hidenavigation=1&theme=dark https://codesandbox.io/s/inspiring-goldberg-utryd?fontsize=14&hidenavigation=1&theme=dark
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.