我正在尝试使用react表、react-csv包和typescript实现下载功能。
我试图使用createRef()创建并使用表组件的引用,但是它引发了以下异常
“类型“refobject”错误中不存在属性“getResolvedState”。
我的代码如下:

import {CSVLink} from "react-csv";
import * as React from 'react';
import ReactTable from 'react-table';

export default class Download extends React.Component<{},{}> {

  private reactTable: React.RefObject<HTMLInputElement>;
  constructor(props:any){
    super(props);
    this.state={} // some state object with data for table
    this.download = this.download.bind(this);
    this.reactTable = React.createRef();
  }

   download(event: any)
   {
    const records =this.reactTable.getResolvedState().sortedData; //ERROR saying getResolved state does not exist
     //Download logic
   }

    render()
    {
       return(
       <React.Fragment>
       <button onClick={this.download}>Download</button>
       <ReactTable
           data={data} //data object
           columns={columns}  //column config object
           ref={this.reactTable}
       />
     </React.Fragment>
    }
}

Any help would be appreciated

最佳答案

您应该发现问题的解决方法是:
修改将reactTableref与<ReactTable />组件as documented here关联的方式,以及
从reacttable ref的getResolvedState()字段访问current
此外,请考虑包装两个渲染元素以确保正确的渲染行为:

/* Note that the reference type should not be HTMLInputElement */
private reactTable: React.RefObject<any>;

constructor(props:any){
  super(props);
  this.state={};
  this.download = this.download.bind(this);
  this.reactTable = React.createRef();
}

download(event: any)
{
   /* Access the current field of your reactTable ref */
   const reactTable = this.reactTable.current;

   /* Access sortedData from getResolvedState() */
   const records = reactTable.getResolvedState().sortedData;

   // shortedData should be in records
}

render()
{
   /* Ensure these are correctly defined */
   const columns = ...;
   const data = ...;

   /* Enclose both elements in fragment, and pass reactTable ref directly */
   return <React.Fragment>
   <button onClick={this.download}>Download</button>
   <ReactTable
       data={data}
       columns={columns}
       ref={ this.reactTable } />
   </React.Fragment>
}

希望能有帮助!

09-19 16:36