You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Router useNavigate卡片跳转失效问题求助

React Router导航失效问题修复

你的代码里有两个核心问题导致点击卡片无法正常导航:

  1. 事件冲突+冗余逻辑:外层div绑定了onClick导航,但Card组件内部已经用Link包裹了整个卡片区域。Link本身就是React Router提供的导航组件,点击时会触发默认导航行为,外层div的onClick事件会被Link的事件冒泡覆盖。另外你的navigateToCardDetails函数只处理了id=1的情况,其他卡片点击后根本不会执行导航逻辑。

  2. 没必要同时用Link和useNavigate:两种方式选一种即可,同时使用只会增加冗余和冲突。


方案一:保留Link组件(推荐,更符合React Router设计)

直接去掉外层div的onClick和useNavigate相关逻辑,利用Card内部的Link完成导航,代码更简洁:

import React from 'react';
import { Link } from 'react-router-dom';

const Card = ({ id, imageSrc, title, text }) => (
  <Link to={`/card/${id}`} className="card-link">
    <div className="rounded-lg overflow-hidden shadow-lg hover:shadow-xl transition duration-300">
      <img src={imageSrc} alt="Card" className="w-full h-auto" />
      <div className="p-4">
        <h3 className="text-xl font-semibold mb-2">{title}</h3>
        <p className="text-gray-700">{text}</p>
      </div>
    </div>
  </Link>
);

const Action = () => {
  const cardsData = [
    { id: 1, imageSrc: '/images/tokyo_ghoul.jpg', title: 'Title 1', text: 'The story follows Ken Kaneki, a student who barely survives a deadly encounter with Rize Kamishiro,his date who reveals herself as a ghoul and tries to eat him. He is taken to the hospital in critical condition. ' },
    { id: 2, imageSrc: '/images/tomodachi.jpg', title: 'Title 2', text: 'High school student Yuuichi Katagiri cherishes his close circle of friends, composed of four classmates: Yutori Kokorogi,Shiho Sawaragi, Makoto Shibe, and Tenji Mikasa. However, when the funds for the upcoming school trip are stolen, the incident causes Shiho and Makoto—who had been tasked with collecting the money—to distance ' },
    { id: 3, imageSrc: '/images/Demon_Slayer.jpg', title: 'Title 3', text: "Ever since the death of his father, the burden of supporting the family has fallen upon Tanjirou Kamado's shoulders.Though living impoverished on a remote mountain, the Kamado family are able to enjoy a relatively peaceful and happy life.One day, Tanjirou decides to go down to the local village to make a" },
    { id: 4, imageSrc: '/images/onepiece2.jpg', title: 'Title 4', text: "A fleet of pirate ships with the same Jolly Roger are shown along with a man sporting said flag, Woonan.Next a night scene where piles of gold treasure are seen bright at sea with a silhouette of Woonan.  Then an island is shown while gold rains down as it fades out ending with a shot of a treasure map." },
    { id: 5, imageSrc: '/images/horimiya-img.jpg', title: 'Title 5', text: 'Admired at school for her friendly attitude and academic achievements, high school student Kyouko Hori has been hiding another side of herself.With her parents often away from home due to work, Hori also has to look after her younger brother and do the housework, leaving no opportunities .' },
    { id: 6, imageSrc: '/images/eminence.jpeg', title: 'Title 6', text: "Even in his past life, Cid's dream wasn't to become a protagonist or a final boss.He'd rather lie low as a minor character until it's prime time to reveal he's a mastermind...or at least, do the next best thing-pretend to be one! And now that he's been reborn into another world, he's ready to set the perfect conditions  to live out his dreams to the fullest." },
    // Add more card data as needed
  ];

  return (
    <div className="grid grid-cols-1 mt-[616px] sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6 p-6">
      {cardsData.map(card => (
        <Card key={card.id} id={card.id} imageSrc={card.imageSrc} title={card.title} text={card.text} />
      ))}
    </div>
  );
};

export default Action;

方案二:改用useNavigate(适合需要额外点击逻辑的场景)

去掉Card组件里的Link,完善navigateToCardDetails函数,让所有卡片都能触发导航:

import React from 'react';
import { useNavigate } from 'react-router-dom';

const Card = ({ imageSrc, title, text }) => (
  <div className="rounded-lg overflow-hidden shadow-lg hover:shadow-xl transition duration-300 cursor-pointer">
    <img src={imageSrc} alt="Card" className="w-full h-auto" />
    <div className="p-4">
      <h3 className="text-xl font-semibold mb-2">{title}</h3>
      <p className="text-gray-700">{text}</p>
    </div>
  </div>
);

const Action = () => {
  const cardsData = [
    { id: 1, imageSrc: '/images/tokyo_ghoul.jpg', title: 'Title 1', text: 'The story follows Ken Kaneki, a student who barely survives a deadly encounter with Rize Kamishiro,his date who reveals herself as a ghoul and tries to eat him. He is taken to the hospital in critical condition. ' },
    { id: 2, imageSrc: '/images/tomodachi.jpg', title: 'Title 2', text: 'High school student Yuuichi Katagiri cherishes his close circle of friends, composed of four classmates: Yutori Kokorogi,Shiho Sawaragi, Makoto Shibe, and Tenji Mikasa. However, when the funds for the upcoming school trip are stolen, the incident causes Shiho and Makoto—who had been tasked with collecting the money—to distance ' },
    { id: 3, imageSrc: '/images/Demon_Slayer.jpg', title: 'Title 3', text: "Ever since the death of his father, the burden of supporting the family has fallen upon Tanjirou Kamado's shoulders.Though living impoverished on a remote mountain, the Kamado family are able to enjoy a relatively peaceful and happy life.One day, Tanjirou decides to go down to the local village to make a" },
    { id: 4, imageSrc: '/images/onepiece2.jpg', title: 'Title 4', text: "A fleet of pirate ships with the same Jolly Roger are shown along with a man sporting said flag, Woonan.Next a night scene where piles of gold treasure are seen bright at sea with a silhouette of Woonan.  Then an island is shown while gold rains down as it fades out ending with a shot of a treasure map." },
    { id: 5, imageSrc: '/images/horimiya-img.jpg', title: 'Title 5', text: 'Admired at school for her friendly attitude and academic achievements, high school student Kyouko Hori has been hiding another side of herself.With her parents often away from home due to work, Hori also has to look after her younger brother and do the housework, leaving no opportunities .' },
    { id: 6, imageSrc: '/images/eminence.jpeg', title: 'Title 6', text: "Even in his past life, Cid's dream wasn't to become a protagonist or a final boss.He'd rather lie low as a minor character until it's prime time to reveal he's a mastermind...or at least, do the next best thing-pretend to be one! And now that he's been reborn into another world, he's ready to set the perfect conditions  to live out his dreams to the fullest." },
    // Add more card data as needed
  ];

  const navigate = useNavigate();

  const navigateToCardDetails = (id) => {
    // 不需要switch判断,直接根据id拼接路径即可
    navigate(`/card/${id}`);
  };

  return (
    <div className="grid grid-cols-1 mt-[616px] sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6 p-6">
      {cardsData.map(card => (
        <div key={card.id} onClick={() => navigateToCardDetails(card.id)}>
          <Card imageSrc={card.imageSrc} title={card.title} text={card.text} />
        </div>
      ))}
    </div>
  );
};

export default Action;

内容的提问来源于stack exchange,提问作者Aman Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 01:22:03