将 React 组件绑定到 Handontable 实例

Binding the React component to a Handontable instance

react-handsontable升级到1.0.0后,我不太确定如何将React组件绑定到Handsontable实例,因为Handsontable现在是一个对等依赖,不再是 React 包装器的一部分,因此不能再通过引用访问它。

react-handsontable 文档展示了如何呈现 Handsontable 组件:

render() {
  return (
    <div id="hot-app">
      <HotTable data={this.data} colHeaders={true} rowHeaders={true} width="600" height="300" stretchH="all" />
    </div>
  );
}

Handsontable 核心 API 参考显示了如何调用其方法:

var ht = new Handsontable(document.getElementById('example1'), options);

所以我尝试向 React 组件添加一个 ID 并创建一个引用该元素的 Handsontable 的新实例,但它最终渲染了另一个 table:

componentDidMount() {
  const hot = new Handsontable(document.getElementById('hot'));
  // hot.countCols();
}

render() {
  return (
    <React.Fragment>
      <HotTable id="hot" settings={...} />
    </React.Fragment>
  );
}

如何将核心 API 方法与呈现的组件一起使用?我还 raised an issue 试图改进文档。

事实证明 HotTable 有一个 hotInstanceHandsontable 的一个实例 – 您仍然需要添加对组件的引用才能访问它。所以按照我之前的例子,它应该看起来像这样:

constructor(props) {
  super(props);
  this.hotRef = React.createRef();
}

componentDidMount() {
  const hotInstance = this.hotRef.current.hotInstance;
  // hotInstance.countCols();
}

render() {
  return (
    <React.Fragment>
      <HotTable ref={this.hotRef} settings={...} />
    </React.Fragment>
  );
}

React.createRef() 的替代方法是 callback refs