React项目中如何为Ant Design的Card组件图标添加可点击跳转事件
解决方法
你之前的写法逻辑颠倒了,Ant Design 的图标组件不会渲染内部嵌套的子元素,所以需要把图标放在<a>标签(或者点击事件容器)内部,正确的代码如下:
// input projects into cards import React from 'react'; import { Card, Avatar, Tag} from 'antd'; import {GithubOutlined,LinkOutlined} from '@ant-design/icons'; const { Meta } = Card; export function ProjectList() { // 如果需要自定义点击事件可以声明这个函数 const handleLinkClick = () => { // 自定义逻辑,比如埋点、内部跳转等 window.open('你的项目预览地址', '_blank'); } return ( <Card style={{ width: 300 }} cover={ <img alt="example" src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png" /> } actions={[ // 写法1:直接用a标签跳转,适合纯外部链接场景 <a href="你的GitHub项目地址" target="_blank" rel="noopener noreferrer" key="github"> <GithubOutlined /> </a>, // 写法2:绑定点击事件,适合需要额外逻辑的场景 <span onClick={handleLinkClick} key="link"> <LinkOutlined /> </span> ]} > <Meta avatar={<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />} title="Card title" description="This is the description" /> </Card> ) };
补充说明
- actions 数组里的每一项都是独立的 React 节点,直接包裹可点击元素即可正常触发跳转/点击事件
- 如果需要保留 Tag 标签,可以把 Tag 和图标一起放在 a 标签内部:
<a href="你的GitHub项目地址" target="_blank" rel="noopener noreferrer" key="github"> <Tag><GithubOutlined /> 查看源码</Tag> </a>
内容的提问来源于stack exchange,提问作者Rob Simanton
相关产品推荐
相关产品推荐

