javascript 使div链接到React元素并传递属性

rbl8hiat  于 2023-01-07  发布在  Java
关注(0)|答案(2)|浏览(157)

我想让它当你点击一个div时,它会把你重定向到另一个页面,就像react router一样,但是我还不知道怎么做。下面是我的代码:

const Card: React.FC = ({ info }: any) => {
  return (
    <div className='card stacked featured'>
      <img src={info.links.mission_patch} className='card_image' alt='NO-IMAGE'/>
      <div className='card_content'>
        <h2 className="card_title">{info.mission_name}</h2>
        <p className='card_number'>Flight: {info.flight_number}</p>
        <p className='card_description'>{info.details}</p>
      </div>
    </div>
  )
}

基本上这是卡片,数据来自一个网络API。我想让它这样,当我点击一张卡片,一个全新的页面显示只有该卡的数据,而不是其他卡,因为他们是迭代。

mzaanser

mzaanser1#

我建议使用react-router-dom中的useNavigate,我就是用它来做这类事情的。

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

const Card: React.FC = ({info}: any) => {
    const navigate = useNavigate()

    return (
        <div className='card stacked featured'>
          <img src={info.links.mission_patch} className='card_image' alt='NO-IMAGE'/>
          <div className='card_content' onClick={() => navigate("/toThePageYouWantToNavigateTo")>
            <h2 className="card_title">{info.mission_name}</h2>
            <p className='card_number'>Flight: {info.flight_number}</p>
            <p className='card_description'>{info.details}</p>
          </div>
          
        </div>
  )
}
y1aodyip

y1aodyip2#

react-router-dom导入并渲染Link组件。

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

...

const Card: React.FC = ({ info }: any) => {
  return (
    <div className='card stacked featured'>
      <img src={info.links.mission_patch} className='card_image' alt='NO-IMAGE'/>
      <Link
        className='card_content'
        to={`"/mission/${info.id}`} // <-- this is path you want to link to
      >
        <h2 className="card_title">{info.mission_name}</h2>
        <p className='card_number'>Flight: {info.flight_number}</p>
        <p className='card_description'>{info.details}</p>
      </Link>
    </div>
  );
};

如果您不想将实际的link/锚标记呈现到DOM中,则导入并使用useNavigate钩子,并向div元素添加onClick处理程序。

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

...

const Card: React.FC = ({ info }: any) => {
  const navigate = useNavigate();

  return (
    <div className='card stacked featured'>
      <img src={info.links.mission_patch} className='card_image' alt='NO-IMAGE'/>
      <div
        className='card_content'
        onClick={() => navigate(`"/mission/${info.id}`)} // <-- this is path you want to link to
      >
        <h2 className="card_title">{info.mission_name}</h2>
        <p className='card_number'>Flight: {info.flight_number}</p>
        <p className='card_description'>{info.details}</p>
      </div>
    </div>
  );
};

相关问题