react中運用event事件觸發子元素標簽進行下載


import React, { Component } from 'react'
import { Button } from 'antd'

class test extends Component {
    constructer(props) {
      super(props)
      this.state= {
       downUrl: '',
      }
    this.checkFiles = this.checkFiles.bind(this)
    this.downClick = this.downClick.bind(this)
    }
    
   checkFiles(event) {
    event.persist() // 為了支持異步回掉后對event事件的繼續引用
    this.setState({ downUrl: res.url }, () => 
    event.target.children[1] && event.target.children[1].click())
    }
   // 阻止a標簽向上冒泡
   downClick(event) {
    event.stopPropagation()
    }

   render() {
    const { downUrl } = this.state
     return(
      <Button onClick={this.checkFiles}>下載<a href={downUrl} download onClick={this.downClick}></a></Button>
      )
   }
} 

 或者自己生成一個<a>標簽直接點擊下載:

const a = document.createElement('a')
a.setAttribute('download', '')
a.setAttribute('href', ‘')
a.click()

 

注:只有 Firefox 和 Chrome 支持 <a>標簽的download 屬性,如果想兼容其他瀏覽器,請用<form>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM