单击 ReactJS 的图像后打开新选项卡

问题描述 投票:0回答:2

我试图在单击hover-img 类后在新选项卡上打开一个新链接(在本例中,我刚刚添加了一个虚拟链接:facebook.com)。但我在做这件事时遇到了一些麻烦。下面是我的代码片段,很乐意感谢您的帮助。

<div className="container">
  {data.map((d)=>(
    <div className="item">
      <img className="background-img" src={d.img} ></img>
      <h3>{d.title}</h3>
      <img 
        className="hover-img" 
        href="www.facebook.com" 
        src="asset/eye.png"
      />
    </div>
  ))}
</div>
reactjs hyperlink tabs onclick href
2个回答
2
投票

您可以单击

href
打开一个新窗口,而不是设置
window.open()
属性。

<div className="container">
{data.map((d)=>(
     <div className="item">
       <img className="background-img" src={d.img} ></img>
       <h3>{d.title}</h3>
       <img 
         className="hover-img" 
         src="asset/eye.png" 
         alt="eye" 
         onClick={()=> window.open("https://www.facebook.com", "_blank")} 
       />
     </div>
    ))}
</div>

0
投票

此代码用于下载任何类型的文件,条件是如果 fileType 是图像,则单击它时它将在新选项卡中打开。这是因为这取决于用户是查看图像还是下载图像。

前端(ReactJs)

const downloadFile = (fileID, fileName) => {
        axios.get(`${URL}/download/${fileID}`, { responseType: 'blob' }).then((res) => {
            const fileType = res.headers['content-type']
            const blob = new Blob([res.data], { type: fileType });
            console.log('image = ',res.data);
            const url = window.URL.createObjectURL(blob);
            if (fileType.includes('image')) {
                window.open(url)
                a.href = null;
                window.URL.revokeObjectURL(url);
            }
            const a = document.createElement('a');
            a.href = url;
            a.download = fileName;
            a.click();
            window.URL.revokeObjectURL(url);
        }).catch((err) => {
            console.log(err.message)
        });

后端(ExpressJs)

app.get('/download/:id',(req,res)=>{ 
    const id = req.params.id;

    connection.query('SELECT path FROM file_table WHERE file_id=?', [id], (err, data) => {
        if (err) {
            res.status(404).json({
                message: err.message
            })
        }
        const filePath = data[0].path;
        res.download(filePath, (err) => {
            if (err) console.log(err);
            else console.log('file is downloaded');
        });
    })
})
© www.soinside.com 2019 - 2024. All rights reserved.