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