如何使用react-router,并将链接导航到特定页面上的特定位置?(例如/home-page#section-three)
细节:
我正在使用react-router我的React应用程序.
我有一个站点范围的导航栏,需要链接到页面的特定部分,如/home-page#section-three.
因此,即使您在说/blog,单击此链接仍将加载主页,第三部分滚动到视图中.这正是标准的<a href="/home-page#section-three>运作方式.
注意:react-router的创建者没有给出明确的答案.他们说它正在进行中,并且同时使用其他人的答案.我会尽力保持这个问题的最新进展和可能的解决方案,直到出现主导的问题.
研究:
这个问题是从2015年(所以10年前的反应时间).最受欢迎的答案是用来HistoryLocation代替HashLocation.基本上这意味着将位置存储在窗口历史记录中,而不是存储在哈希片段中.
坏消息是......即使使用HistoryLocation(大多数教程和文档在2016年所说的内容),锚标签仍然不起作用.
https://github.com/ReactTraining/react-router/issues/394
ReactTraining上的一个线程,关于如何使用anchor链接与react-router.这是没有确认的答案.要小心,因为大多数建议的答案都已过时(例如使用"哈希"道具<Link>)
看起来很奇怪,当我打开/时,浏览器会/#/?_k=dlo2cz在地址中显示类似的内容.每次刷新页面或切换到其他路径时,随机查询字符串值都会更改.
代码被复制并粘贴在react-router分支上1.0.0-rc1.
import React from 'react';
import { Router, Route, Link, IndexRoute } from 'react-router';
const App = React.createClass({
render() {
return (
<div>
<h1>App</h1>
{/* change the <a>s to <Links>s */}
<ul>
<li><Link to="/about">About</Link></li>
<li><Link to="/inbox">Inbox</Link></li>
</ul>
{/*
next we replace `<Child>` with `this.props.children`
the router will figure out the children for us
*/}
{this.props.children}
</div>
)
}
});
const Message = React.createClass({
render() {
return <h3>Message</h3>
}
});
const About …Run Code Online (Sandbox Code Playgroud) 我对React比较陌生; 如果这是一个非常天真的问题,请道歉.
有什么技术优势browserHistory使它更适合hashHistory?例如,使用History API是否会提高性能/效率?
虽然这是以额外的服务器配置为代价并且需要通过basename对不同服务器的基本URL进行硬编码或配置,但是文档声明browserHistory是推荐的.
hashHistory但是,"只是工作",无论提供文件的基本URL如何.无需服务器配置.捆绑您的应用程序,从服务器上的任何URL /路径托管它,很好.
如果文档进一步解释为什么browserHistory推荐它,即使它涉及更多的复杂性,这可能是好的.
我刚刚在 c-panel 上部署了我的 React 应用程序构建。该应用程序包括不同的路线,每次我尝试到达其中一条路线时,我都会得到404 Not found。例如,如果我尝试访问http://example.com/它,它将进入该网站,如果我按下链接到它的按钮,http://example.com/articles它将起作用。http://example.com/articles但是,如果我尝试从我共享的链接获取或仅输入此地址,我会得到404 Not found. 当我在本地主机上运行开发模式时,不会发生这种情况。
我更改了 package.json 中的主页 url "homepage": "http://example.com",,但没有效果。
我的应用程序根目录包含<Router>
function App() {
return (
<Provider store={store}>
<Router>
<React.Fragment>
<CssBaseline />
<Header title="exampletitle" />
<MobileHeader />
<Main />
<BottomNavbar />
</React.Fragment>
</Router>
</Provider>
);
}
Run Code Online (Sandbox Code Playgroud)
这是由路由操纵的 Main.js 组件。
function Main(props) {
return (
<div>
<Switch>
<Route exact path="/" component={Homepage} />
<Route exact path="/about" component={About} />
<Route exact path="/signup" component={Registerpage} />
<Route …Run Code Online (Sandbox Code Playgroud)