首页 > 解决方案 > React JS:单击下载按钮以 JSON 格式下载文件

问题描述

我想使用从该行的值传递的值下载与该行有关的文件,即使在我单击下载按钮之前,该文件也已创建和下载,我正在使用 react-file-download 包和 filedownload 方法相同,但不能这样做。我需要有关如何解决此问题的意见:

class displayBlank {

handleDownload(col 1,col2)
{

    var data = "This is an example JSON";
    var fileDownload = require('react-file-download');
    fileDownload(data, 'filename.json');

}

render(){
                    <table >
                      <thead>
                        <tr role="row">
                          <th>COL 1</th>
                          <th>COL 2</th>
                          <th>COL 3</th>
                          <th>COL 4</th>
                          <th>COL 5</th>
                          <th>COL 6</th>
                          <th>COL 7</th>
                          <th>COL 8</th>
                          <th>COL 9</th>
                        </tr>
                      </thead>
                      <tbody>
                        {this.state.pageOfItems.map((item, i) => {
                          return (
                            <tr key={i}>
                              <td >{item.COL1}</td>
                              <td> {item.COL2}</td>
                              <td> {item.COL3}</td>  
                              <td> {item.COL4}</td>  
                              <td> {item.COL5}</td>
                              <td> {item.COL6}</td>
                              <td style={{color: 'white', fontWeight: 'bold', backgroundColor: item.COL 7 === 'VALUE' ? 'red' : 'green'}}>{item.COL7}</td>
                              <td >{item.COL 8 === 'VALUE1' ? (<div><Button bsStyle="primary" type="submit" bsSize="small" onClick={this.handleDownload(item.COL1,item.COL2)}>DOWNLOAD</Button></div>) : (<div></div>)}</td>
                            </tr>
                          );
                        })}


                      </tbody>
                    </table>
                    }
                    }

该文件甚至在单击下载按钮之前就已下载,并且特定的行值没有传递到 handleDownload 函数。

标签: javascriptreactjs

解决方案


onClick={() => this.handleDownload(item.COL 1,item.COL 2)}

您正在调用该函数,而是应该使用上面的回调。


推荐阅读