![](/img/trans.png)
[英]How to reference a React Component class from outside the render function?
[英]How to render component from a function outside the render method in React?
我有一个React类,其中Im使用一个名为React CSV的插件,该插件将值数组转换为CSV并开始在浏览器中下载新创建的CSV文件。
单击名为“导出”的按钮时,我会调用一个函数。 该函数在render函数之外(尽管与React类相同)。 呈现后,该组件会立即触发CSV文件的下载。
我的按钮组件,位于render()方法内部:
<Button
variant="contained"
color="secondary"
onClick={this.exportCSV.bind(this)}
>
Export
</Button>
我的exportCSV函数在render方法之前定义如下:
exportCSV(){
const csvMergedData = this.props.dataA.map((value, index)
=> ({
columnA: value,
columnB: this.props.dataB[index]
}));
return (<CSVDownload data={csvMergedData} /> );
}
问题是,CSVDownload组件未安装/渲染,因此没有下载CSV文件。
如何渲染组件?
PS:我已经解决了其他问题,但是找不到解决方案。
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 });
}
最后,在您的render方法中,您可以根据状态有条件地渲染CSVDownload
组件:
<Button
variant="contained"
color="secondary"
onClick={this.exportCSV.bind(this)}
>
Export
</Button>
{this.state.csvMergedData
? <CSVDownload data={this.state.csvMergedData} />
: null
}
实际上,您不能以这种方式渲染react组件。 一个适合您的解决方案是
class SomeComponent extends React.Component {
state = {
data: false
}
exportCsv = () => {
const data = this.props.dataA.map((value, index)
=> ({
columnA: value,
columnB: this.props.dataB[index]
}));
this.setState({ data })
}
render() {
return <React.Fragment>
<Button
variant="contained"
color="secondary"
onClick={this.exportCsv}
>
Export
</Button>
{ this.state.data ? <CSVDownload data={this.state.data} /> : null}
</React.Fragment>
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.