首页 > 解决方案 > 如何在反应打字稿中将 ref 添加到 CSVLINK?

问题描述

从服务器加载数据后,我想单击 CSV 下载链接。我尝试了https://github.com/react-csv/react-csv/issues/237中的所有方法

const csvLinkRef = React.useRef<CSVLink & HTMLAnchorElement & { link?: HTMLAnchorElement }>();

<CSVLink
  ref={csvLinkRef}
  data={tableDataToDownLoadAsCSV}
/>

它给了我以下错误

标签: reactjstypescriptreact-reduxexport-to-csv

解决方案


看看这段代码,它将有助于调整你的代码

export default function dataListPage(props: DataListProps) {
const csvLinkRef = useRef<
    CSVLink & HTMLAnchorElement & { link: HTMLAnchorElement }
  >(null); // setup the ref that we'll use for the hidden CsvLink click once we've updated the data

const [data, setData] = useState<dataTypeObj[]>([]);

 const hanldeExportButton = async () => {
    const data: dataTypeObj[] = await fetchData();
    setData(data);
    csvLinkRef?.current?.link.click();
  };

 return (
<CSVLink
        data={data}
        className="exportButton"
        filename="file.csv"
        ref={csvLinkRef}
      >
      </CSVLink>
        <Button
          color="primary"
          variant="contained"
          size="small"
          startIcon={<GetAppIcon />}
          onClick={hanldeExportButton}
        >
          Export As CSV
        </Button>
        );
} //func dataListPage end

推荐阅读