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>標籤直接點擊下載:react

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

 

注:只有 Firefox 和 Chrome 支持 <a>標籤的download 屬性,若是想兼容其餘瀏覽器,請用<form>瀏覽器

相關文章
相關標籤/搜索