我有一个 React 类,其中我使用了一个名为React CSV的插件,该插件将一组值转换为 CSV 并开始在浏览器中下载新创建的 CSV 文件。
当单击名为“导出”的按钮时,我会调用一个函数。这个函数在渲染函数之外(虽然是同一个 React 类)。该组件在渲染后立即触发 CSV 文件的下载。
我的按钮组件,在 render() 方法中:
<Button
variant="contained"
color="secondary"
onClick={this.exportCSV.bind(this)}
>
Export
</Button>
我在 render 方法之前定义的 exportCSV 函数如下:
exportCSV(){
const csvMergedData = this.props.dataA.map((value, index)
=> ({
columnA: value,
columnB: this.props.dataB[index]
}));
return (<CSVDownload data={csvMergedData} /> );
}
问题是,CSVDownload 组件未安装/呈现,因此未下载 CSV 文件。
如何渲染组件?
PS:我已经看过其他SO答案,但找不到解决方案。
该CSVDownload
组件没有安装,因为从一个事件处理函数返回的组件不呈现组件。为了渲染一个组件,它需要在 render 方法中。
我建议放入csvMergedData
组件的状态并将其初始化为 null:
class YourComponent extends React.Component {
state = { csvMergedData: null };
然后在您的exportCSV
函数中,您可以进行映射并将其保存在状态中:
exportCSV() {
const csvMergedData = this.props.dataA.map((value, index) => ({
columnA: value,
columnB: this.props.dataB[index]
}));
this.setState({ csvMergedData });
}
最后在您的渲染方法中,您可以CSVDownload
根据状态有条件地渲染组件:
<Button
variant="contained"
color="secondary"
onClick={this.exportCSV.bind(this)}
>
Export
</Button>
{this.state.csvMergedData
? <CSVDownload data={this.state.csvMergedData} />
: null
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句