如何从JavaScript数组提取外部链接并实现按钮跳转功能?
解决React中点击按钮跳转外部链接的问题
这里给你两种简单直接的实现方式,都能满足点击「Try Me」按钮跳转到对应项目外部链接的需求:
方法一:用<a>标签模拟按钮(最简洁)
直接把按钮替换成<a>标签,设置href为数组里的path,同时添加target="_blank"在新窗口打开,加上rel="noopener noreferrer"避免安全风险。这种方式不需要额外写函数,代码更简洁:
{portfolios.map(({id, src, path}) => ( <div key={id} className='shadow-md shadow-gray-600 rounded-lg'> <img src={src} alt="" className='rounded-md duration-200 hover:scale-105'/> <div className='flex items-center justify-center'> <a href={path} target="_blank" rel="noopener noreferrer" className='w-1/2 px-6 py-3 m-4 duration-200 hover:scale-105 no-underline text-white' > Try Me </a> </div> </div> ))}
注:如果之前用
<a>标签没成功,大概率是没加target="_blank"或者没覆盖默认的a标签样式(比如下划线、文字颜色),上面的no-underline text-white可以保证样式和原按钮一致。
方法二:按钮绑定点击事件(更灵活)
如果需要在跳转前做额外逻辑(比如埋点、校验),可以给按钮绑定点击事件,通过window.open实现跳转:
步骤1:定义跳转函数
在组件内部添加一个处理跳转的函数:
const handleNavigate = (path) => { // 这里可以加跳转前的逻辑,比如日志上报 window.open(path, '_blank', 'noopener,noreferrer'); };
步骤2:给按钮绑定点击事件
修改按钮部分的代码,把onClick事件指向这个函数:
{portfolios.map(({id, src, path}) => ( <div key={id} className='shadow-md shadow-gray-600 rounded-lg'> <img src={src} alt="" className='rounded-md duration-200 hover:scale-105'/> <div className='flex items-center justify-center'> <button onClick={() => handleNavigate(path)} className='w-1/2 px-6 py-3 m-4 duration-200 hover:scale-105' > Try Me </button> </div> </div> ))}
完整组件代码示例
以下是整合了方法二的完整组件代码:
const Portfolio = () => { const portfolios = [ { id: 1, src: Apsnip, path: 'https://rapidapi.com/ChristopherTheDevCo/api/crpytonux/', }, { id: 2, src: Hdysnip, path: 'https://rapidapi.com/ChristopherTheDevCo/api/crpytonux/' }, { id: 3, src: Hhsnip, path: 'https://rapidapi.com/ChristopherTheDevCo/api/crpytonux/' }, { id: 4, src: Rsnip, path: 'https://rapidapi.com/ChristopherTheDevCo/api/crpytonux/' }, ]; const handleNavigate = (path) => { window.open(path, '_blank', 'noopener,noreferrer'); }; return ( <div name='portfolio' className=' bg-gradient-to-b from-black to bg-purple-950 w-full text-white md:h-screen'> <div className='max-w-screen-lg p-4 mx-auto flex flex-col justify-center w-full h-full'> <div className='pb-8'> <p className='text-4xl font-bold inline border-b-4 border-gray-500'>Some Creations</p> <p className='py-6'>These are some of my projects. You can review them here.</p> </div> <div className='grid sm:grid-cols-2 md:grid-cols-3 gap-8 px-12 sm:px-0'> {portfolios.map(({id, src, path}) => ( <div key={id} className='shadow-md shadow-gray-600 rounded-lg'> <img src={src} alt="" className='rounded-md duration-200 hover:scale-105'/> <div className='flex items-center justify-center'> <button onClick={() => handleNavigate(path)} className='w-1/2 px-6 py-3 m-4 duration-200 hover:scale-105' > Try Me </button> </div> </div> ))} </div> </div> </div> ); };
内容的提问来源于stack exchange,提问作者LucidVisionary
相关产品推荐
相关产品推荐

