【问题标题】:React-Table: exception thrown calling 'getResolvedState()' on component refReact-Table:在组件 ref 上调用“getResolvedState()”引发异常
【发布时间】:2019-09-15 17:37:33
【问题描述】:

我正在尝试使用 React Table、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

【问题讨论】:

    标签: reactjs typescript ref react-table


    【解决方案1】:

    您应该发现问题已通过以下方式解决:

    1. 修改将reactTable 引用与&lt;ReactTable /&gt; 组件as documented here 关联的方式,并且
    2. 从你的 reactTable ref 的 current 字段访问 getResolvedState()

    另外,考虑包装两个渲染元素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>
    }
    

    希望有帮助!

    【讨论】:

    • 谢谢!现在它的抛出“对象可能为空!属性'getResolvedState'在类型'HTMLDivElement'上不存在。”
    • 太好了 - 很高兴我能帮上忙 :-)
    • 请问您能在新帖子中发布这个问题吗?并把链接发给我?在 cmets 区域中理解您的问题有点困难 :-)
    猜你喜欢
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多