Fork me on GitHub

react中运用event事件触发子元素<a>标签进行下载

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>

posted @ 2018-01-23 10:29  天满  阅读(4785)  评论(0编辑  收藏  举报