React-Table:在组件引用上调用'getResolvedState()'的异常抛出

问题描述 投票:1回答:1

我正在尝试使用React Table,react-csv包和TypeScript来实现下载功能。

我正在尝试使用createRef()创建和使用表组件的引用,但它抛出以下异常

“属性'getResolvedState'在类型'RefObject'上不存在”错误。

我的代码如下:

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
reactjs typescript ref react-table
1个回答
1
投票

您应该通过以下方式找到问题:

  1. 修改你将reactTable ref与你的<ReactTable />组件as documented here联系起来的方式,以及
  2. 从reactTable ref的getResolvedState()字段访问current

另外,考虑包装两个渲染的元素with a fragment以确保正确的渲染行为:

/* 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>
}

希望有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.