在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试图改善文档。
最佳答案
事实证明,HotTable
有一个hotInstance
– Handsontable
的实例–并且您仍然需要添加对组件的引用才能访问它。因此,按照我之前的示例,它应该类似于以下内容:
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。