我在React.js中有一个按钮,点击一下即可将数据发送到服务器以转换为CSV文件。当我收到回复时,我希望能够让用户下载CSV文件。它适用于Firefox和Chrome,但不适用于Safari。有任何想法吗?我知道HTMLElement.click()不支持.click()。
这是我的代码:
import React from 'react';
import { graphql } from 'react-apollo';
import ExportDataQL from 'ExportDataQL'
import Icon from 'Icon';
const handleExport = (data, type, exportToCSV) => {
const variables = {
data: JSON.stringify(data),
type
}
exportToCSV({ variables })
.then( response => {
const { fileName, fileUri } = response.data.exportToCSV
var hiddenElement = document.createElement('a');
hiddenElement.href = fileUri;
hiddenElement.target = '_blank';
hiddenElement.download = fileName;
document.body.appendChild(hiddenElement);
console.log('clicking')
// hiddenElement.click();
hiddenElement.dispatchEvent(new MouseEvent(`click`, {bubbles: true, cancelable: true, view: window}))
hiddenElement.remove()
})
.catch( e => console.log('ERROR getting download URL:', e) )
}
const ExportToCSV = ({ data, dataType, buttonText, exportToCSV }) => {
if (data === undefined || data.length===0) return <span></span>
return <button
type='button'
className="btn btn-link hover_cursor font-weight-bold"
onClick={() => handleExport(data, dataType, exportToCSV)}>
<Icon IconClassName="fill-primary" icon='excel-file'/><span className="ml-2">
{buttonText ? buttonText : "Export data"}</span>
</button>
}
export default graphql(ExportDataQL.exportToCSV, {name: "exportToCSV"})(ExportToCSV);