如何为React Styled Components中的React图标设置外部链接?
为React图标添加外部链接的解决方案
你遇到的问题是因为FaFacebookF、FaInstagram这类图标组件本身不支持href或to属性(to是React Router内部路由专用属性),外部跳转需要依赖原生<a>标签实现。以下是两种可行的实现方式:
方式一:用原生a标签包裹图标组件
直接在图标外层套<a>标签,设置跳转链接及安全属性:
修改index.js代码:
<SocialWrapper> <a href="你的Facebook官方链接" target="_blank" rel="noopener noreferrer" style={{ textDecoration: 'none', cursor: 'pointer' }} > <FacebookIcon /> </a> <a href="你的Instagram官方链接" target="_blank" rel="noopener noreferrer" style={{ textDecoration: 'none', cursor: 'pointer' }} > <InstagramIcon /> </a> </SocialWrapper>
target="_blank":让链接在新窗口打开rel="noopener noreferrer":避免安全风险,这是外部链接的标准配置- 内联样式
textDecoration: 'none'用来去掉a标签默认的下划线
如果想统一管理样式,也可以用styled-components封装一个链接组件:
// styles.js export const SocialLink = styled.a` text-decoration: none; cursor: pointer; `
然后在index.js里替换原生a标签:
<SocialWrapper> <SocialLink href="你的Facebook链接" target="_blank" rel="noopener noreferrer"> <FacebookIcon /> </SocialLink> <SocialLink href="你的Instagram链接" target="_blank" rel="noopener noreferrer"> <InstagramIcon /> </SocialLink> </SocialWrapper>
方式二:将图标整合到styled链接组件中
这种方式可以简化代码,把图标和链接样式合并:
修改styles.js,移除原有的FacebookIcon、InstagramIcon,创建通用的社交链接组件:
export const SocialWrapper = styled.div` width: 100%; display: flex; gap: 10px; margin-bottom: 10px; ` export const SocialLink = styled.a` color: ${white}; font-size: 2.3rem; text-decoration: none; cursor: pointer; &:hover { color: ${red}; } `
然后在index.js中直接使用:
<SocialWrapper> <SocialLink href="你的Facebook链接" target="_blank" rel="noopener noreferrer"> <FaFacebookF /> </SocialLink> <SocialLink href="你的Instagram链接" target="_blank" rel="noopener noreferrer"> <FaInstagram /> </SocialLink> </SocialWrapper>
内容的提问来源于stack exchange,提问作者user19024715
相关产品推荐
相关产品推荐

