用React Link标签导航到另一页的特定部分

发布于 2025-02-06 06:57:50 字数 239 浏览 1 评论 0原文

假设我在标题上有一个称为“联系我”的按钮。 当我单击按钮时,即使我在另一页上,它也会将我重定向到主页的联系部分。

我将如何使用React Link标签进行设置?我尝试这样使用它,

 <Link to="/#contactsec" > contact Me <Link>

它将我重定向到主页,但我不转到主页的Contactsec。

我如何做到这一点。

let's say I have a button called 'contact me' on the header.
when I click on the button it will redirect me to the contact section of the home page even though I am on the other page.

how will I set this up with react Link tag? i try to use it like this

 <Link to="/#contactsec" > contact Me <Link>

it redirects me to the home page but I do not go to the contactsec of the home page.

how I can do this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

绿萝 2025-02-13 06:57:50

使用使用效果挂钩抓住标识符(“#”符号之后的URL的一部分),在页面上找到具有相同ID的元素,然后在其存在的情况下平滑滚动。

useEffect(() => {
  const href = window.location.href.substring(
    window.location.href.lastIndexOf('#') + 1
  );
  const element = document.getElementById(href);
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' });
  }
}, []);

Use a useEffect hook to grab the identifier (the portion of the URL after the '#' symbol), locate an element with the same ID on the page, and then smoothly scroll to it if it exists.

useEffect(() => {
  const href = window.location.href.substring(
    window.location.href.lastIndexOf('#') + 1
  );
  const element = document.getElementById(href);
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' });
  }
}, []);
寂寞美少年 2025-02-13 06:57:50
 const navigate = useNavigate();
 const navigateToContact = () => {
 navigate("/");
 setTimeout(() => {
  const contactSection = document.getElementById("contact");
  if (contactSection) {
    contactSection.scrollIntoView({ behavior: "smooth" });
  }
}, 100); // Delay for smoother scroll

};

//通过使用此方法按钮

<button onClick={navigateToContact}>Contact us</button>

,当单击按钮时,它将重定向到主页,然后将ID“触点”顺畅地滚动到该部分。

 const navigate = useNavigate();
 const navigateToContact = () => {
 navigate("/");
 setTimeout(() => {
  const contactSection = document.getElementById("contact");
  if (contactSection) {
    contactSection.scrollIntoView({ behavior: "smooth" });
  }
}, 100); // Delay for smoother scroll

};

//button

<button onClick={navigateToContact}>Contact us</button>

By using this approach, when the button is clicked, it will redirect to the home page and smoothly scroll to the section with the ID "contact".

拥有 2025-02-13 06:57:50

我不知道它是否适合您想要的用户体验,但是解决方案是在另一个选项卡中打开它,例如

&lt; link =“/#Contactsec” target =“ _ black”&gt;与我联系; link&gt;

I don't know if it'll fit the user experience you want, but a solution is to open it in another tab, like this

<Link to="/#contactsec" target="_blank" > contact Me <Link>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文