我正沿着这样的路线航行:
<Link to="/products#product5">Go to projects and focus id</Link>该链接的目标是转到页面并将焦点转到id。但这不会发生的。相反,我要登陆products页面,而不是专注于id。正确的处理方法是什么?它只需要从指定的链接。
这是我的尝试:Hello.tsx
import React from "react";
import { Link } from "react-router-dom";
export default ({ name: string }) => (
<div>
<h1>Hello {name}!</h1>
<Link to="/products#product5">Go to projects and focus id</Link>
</div>
);以下是产品页面:
import React from "react";
import { Link, Route, Switch, Redirect } from "react-router-dom";
import "./products.scss";
const Shoes = React.lazy(() => import("./shoes/shoes.component"));
const Cloths = React.lazy(() => import("./cloths/cloths.component"));
export default class Products extends React.Component {
render() {
return (
<div>
<header>
<Link to="/products/shoe">Shoes</Link>
<Link to="/products/cloths">Cloths</Link>
</header>
<h1>Products page</h1>
<main>
<Switch>
<Redirect exact from="/products" to="/products/shoe" />
<Route path="/products/shoe">
<Shoes />
</Route>
<Route path="/products/cloths">
<Cloths />
</Route>
</Switch>
</main>
</div>
);
}
}默认鞋页: id需要查看的位置
import React from "react";
import "./shoes.style.scss";
export default class Shoes extends React.Component {
render() {
return (
<div className="list-shoes">
<h1>I am from shoe page </h1>
<span>Product-1</span>
<span>Product-2</span>
<span>Product-3</span>
<span>Product-4</span>
<span>Product-5</span>
<span>Product-6</span>
<span>Product-7</span>
<span>Product-8</span>
<span id="product9">Product-9</span>
<span>Product-10</span>
</div>
);
}
}正确的方法是什么?提前谢谢。
发布于 2021-01-01 17:41:49
如果您尝试从/products/shoe路由(如/products/shoe#product9 )直接访问产品,您可以看到当前的方法运行良好。id product9存在于您的Shoes组件中,因此当您进入该路由时,它会自动聚焦。
但是,您在问题中指定的路由的问题是由以下重定向引起的:
<Redirect exact from="/products" to="/products/shoe" />正如您在所提供的示例中所看到的,当您尝试访问/products#product5时,所发生的情况是您被自动重定向到/products/shoe。在重定向期间没有保留散列参数,因此页面不会滚动到原始中包含的id (不再有一个可以聚焦的id )。
如果您想让它工作,将需要手动检索哈希值,并在触发重定向之前将其附加到目标URL。您可以通过使用render组件的Route方法来访问反应路由器提供的location对象,然后使用它构建要重定向到的URL。
<Route exact path="/products"
render={({ location }) => <Redirect to={{
pathname: '/products/shoe',
hash: location.hash,
}}
/>使用这段代码,散列的值将被添加到新的url中,因此在重定向过程中不应该丢失要聚焦的项的id。回到示例路径,/products#product5现在将重定向到/products/shoe#product5而不是/products/shoe。
https://stackoverflow.com/questions/65531530
复制相似问题