【问题标题】:How to render component from a function outside the render method in React?如何从 React 中的 render 方法之外的函数渲染组件?
【发布时间】:2018-12-14 03:17:19
【问题描述】:

我有一个 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 答案,但找不到解决方案。

【问题讨论】:

    标签: javascript reactjs csv dom


    【解决方案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>
      }
    }
    

    【讨论】:

      【解决方案2】:

      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
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-19
        • 2019-09-01
        • 2020-03-26
        • 2019-11-22
        • 2020-06-09
        • 2017-03-17
        • 2018-09-09
        相关资源
        最近更新 更多