【问题标题】:How to make links work with card-img-overlay React如何使链接与 card-img-overlay React 一起使用
【发布时间】:2021-03-08 05:09:37
【问题描述】:

我的项目有问题。我创建了一个 card-img-overlay 来在图像上显示图标。如果您单击整个图像,您将被重定向到一个帖子。我想让喜欢和分享的图标可以点击。

我的项目在 Reactjs 中。我正在显示来自 Reddit API 的图像和视频。

感谢您的帮助。

  id,
  slugTitle,
  title,
  url_overridden_by_dest,
  author,
  preview,
}) => {
  const [isVideo, setIsVideo] = useState(false);
  useEffect(() => {
    if (preview) setIsVideo(preview.split('.').pop() === 'mp4');
  }, [preview]);
  const history = useHistory();

  const goToPage = () => {
    history.push(`/Post/${id}/${slugTitle}`);
  };

  return (
    <Card
      inverse
      onClick={goToPage}
      style={{
        cursor: 'pointer',
      }}
    >
      {isVideo && (
        <video autoPlay="false" loop width="100%" src={preview}>
          <track default kind="captions" />
        </video>
      )}
      {!isVideo && (
        <CardImg top width="100%" src={url_overridden_by_dest} alt={title} />
      )}
      <CardImgOverlay className="hideinfos">
        <CardText className="w-100 d-flex justify-content-between">
          <div>
            <VscAccount className="mr-2" size={20} />
            {author}
          </div>
          <div>
            <LikeButtonhp
              className="mr-2 card-link"
              size={20}
              style={{
                position: 'relative',
              }}
            />
            <BiShareAlt size={20} />
          </div>
        </CardText>
      </CardImgOverlay>
    </Card>
  );
};

【问题讨论】:

    标签: reactjs hyperlink reactstrap card


    【解决方案1】:

    您需要将onClick 处理程序放在您的LikeButtonhpBiShareAlt 组件上,并使用event.stopPropagation() 阻止事件冒泡到&lt;Card /&gt;

    <BiShareAlt
        size={20}
        onClick={event => {
            event.stopPropagation();
            // Do stuff for share click
        }}
    />
    

    您可能还需要更改 BiShareAltLikeButtonhp 组件以支持 onClick 属性,例如,如果它们呈现 &lt;button&gt; 元素,它可能如下所示:

    const BiShareAlt = ({ onClick }) => (
        <button onClick={onClick}>
            Share
        </button>
    );
    
    export default BiShareAlt;
    

    【讨论】:

    • 您好,马特,感谢您的帮助。它解决了我的问题。
    【解决方案2】:

    在我的 onClick 中,我添加了一个 e.stopPropagation();它解决了我的问题。现在我可以点击心形图标,它就可以工作了。它会停止在我的图像(父级)上设置 onClick。

    function LikeButtonhp() {
      const [liked, setLiked] = useState(false);
      return (
        <Button
          outline
          color="link"
          className="likebutton"
          onClick={(e) => {
            e.stopPropagation();
            setLiked(!liked);
          }}
          style={{ color: 'white' }}
        >
          {liked ? <BsHeartFill size={20} /> : <BsHeart size={20} />}
        </Button>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 2015-10-16
      • 2019-11-17
      相关资源
      最近更新 更多