如何在React中的render方法之外的函数中渲染组件?

时间:2018-07-05 15:09:36

标签: javascript reactjs csv dom

我有一个React类,其中Im使用名为React CSV的插件,该插件将值数组转换为CSV并开始在浏览器中下载新创建的CSV文件。

单击名为“导出”的按钮时,我会调用一个函数。该函数在render函数之外(尽管与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答案,但是找不到解决方案。

2 个答案:

答案 0 :(得分:1)

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
}

答案 1 :(得分:1)

实际上,您不能以这种方式渲染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>
  }
}
相关问题