将React组件绑定到Handontable实例

时间:2018-06-25 09:23:02

标签: javascript reactjs handsontable

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 Core API参考说明了如何调用其方法:

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

因此,我尝试向React组件添加一个ID,并创建一个引用该元素的Handsontable的新实例,但是它最终呈现了另一个表:

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

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

如何在渲染的组件上使用Core API方法?我也raised an issue试图改善文档。

1 个答案:

答案 0 :(得分:1)

事实证明,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>
  );
}

callback refsReact.createRef()的替代方法。