【问题标题】:How to add a link to another website after clicking on Card in React JS在 React JS 中单击 Card 后如何添加指向另一个网站的链接
【发布时间】:2021-07-08 19:06:09
【问题描述】:

下面是我的 Cards.js 文件的代码,现在它是一张你可以点击的卡片,它链接到同一个网站中路径 ='/services' 的服务页面,我想添加一个链接到另一个网站,我该怎么做呢?我需要向 Cards.js 添加一个 href= 链接吗?

import React from 'react';
import CardItem from './CardItem';
import './Cards.css'

function Cards() {
 return (
  <div className='cards'>
    <h1>Check out my Programming Portfolio Projects!</h1>
    <div className='cards__container'>
      <div className='cards__wrapper'>
        <ul className="cards__items">
          <CardItem 
          src={`${process.env.PUBLIC_URL}/images/ReactSocialPosts.jpg`}
          text='hello testing 123'
          label='This is a card'
          path ='/services'
          />
        </ul>
      </div>
    </div>
  </div>
 )
}

export default Cards;

如果需要,下面是 CardItem.js

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

function CardItem(props) {
  return (
    <>
      <li className='cards__item'>
        <Link className='cards__item__link' to={props.path}>
          <figure className='cards__item__pic-wrap' data-category={props.label}>
            <img
              src={props.src}
              alt='Travel Image'
              className="cards__item__img"
            />
          </figure>
          <div className='cards__item__info'>
            <h5 className='cards__item__text'>{props.text}</h5>
          </div>
        </Link>
      </li>
    </>
  );
}

export default CardItem;

【问题讨论】:

    标签: javascript html css reactjs hyperlink


    【解决方案1】:

    我不确定,但我认为您只需创建第二个 CardItem,其属性为 path = complete link to external website

    例子:

     <CardItem 
              src={`${process.env.PUBLIC_URL}/images/OtherImage.jpg`}
              text='External website'
              label='A label'
              path ='https://externalwebsite.com'
              />
    

    【讨论】:

      【解决方案2】:

      如果你只是想简单地链接到另一个网站,那么你可以简单地使用一个锚标签,如果你想从 react-router-dom 声明一个路由以便该链接跟随,你需要看看这个post

      【讨论】:

        【解决方案3】:

        根据文档,React-Router 仅了解内部路径。然后需要一个锚标记。我会为 Link 做一个包装器组件,选择是渲染锚点还是路由器链接对象。然后用它代替“链接”。

        类似(代码未测试):

        const MyLink = ({path, children, ...props}) => {
            const comp = path?.trim().substring(0,4) === "http" ? <a href={path}> : <Link to={path}>;
            return <comp ...props>{children}</comp>
        };
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-07-20
          • 2012-09-10
          • 2020-08-25
          • 1970-01-01
          • 2022-08-04
          • 1970-01-01
          • 1970-01-01
          • 2021-11-20
          相关资源
          最近更新 更多