Jor*_*llo 2 javascript reactjs react-router react-router-dom
我正在开发一个带有补丁说明的应用程序,其中的 url 具有使用 React Router 定义的以下结构:
<Route path='/updates/:id?' render={(params) => <Updates {...params} />}></Route>
Run Code Online (Sandbox Code Playgroud)
如果 url 包含这样的哈希部分,我希望允许用户转到文档的特定部分/updates/1#index
。在这里, url 部分应该像普通 HTML 一样#index
将用户发送到 div 。id='index'
我读到了有关普通 HTML 的 hashRouter 的信息,{content}
但它没有按我的预期或要求工作:
<HashRouter>
{content}
</HashRouter>
Run Code Online (Sandbox Code Playgroud)
我怎样才能实现这个目标?
也许您可以用来Element#scrollIntoView()
模仿锚链接的默认浏览器行为。
例如,如果<Updates />
是托管补丁说明内容的组件(其中定义了锚链接),那么您可以在安装或启动时运行此函数<Updates />
来实现此目的:
function scrollToHash() {
/* Obtain hash from current location (and trim off leading #) */
const id = window.location.hash.substr(1);
if(id) {
/* Find matching element by id */
const anchor = document.getElementById(id);
if(anchor) {
/* Scroll to that element if present */
anchor.scrollIntoView();
}
}
}
/* Usage example */
function Updates() {
React.useEffect(() => {
scrollToHash();
},[]);
/* Render patch content that contains anchors */
return <div> ... </div>
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3157 次 |
最近记录: |