Handsontable&React

Tim*_*Tim 6 javascript handsontable reactjs

我开始反应并尝试在我的反应应用程序中设置动手表: 反应 - 动手

// import React...
import React from 'react';
import ReactDOM from 'react-dom';

// ... Handsontable with its main dependencies...
import moment from 'moment';
import numbro from 'numbro';
import pikaday from 'pikaday';
import Zeroclipboard from 'zeroclipboard';
import Handsontable from 'handsontable';

// ... and HotTable
import HotTable from 'react-handsontable';

class ExampleComponent extends React.Component {
  constructor(props) {
    super(props);
    this.handsontableData = [
      ["", "Ford", "Volvo", "Toyota", "Honda"],
      ["2016", 10, 11, 12, 13],
      ["2017", 20, 11, 14, 13],
      ["2018", 30, 15, 12, 13]
    ];
  }

  render() {
    return (
      <div id="example-component">
        <HotTable root="hot" data={this.handsontableData} colHeaders={true} rowHeaders={true} width="600" height="300" stretchH="all" />
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止工作,但我如何获得像纯JavaScript一样的表的实例

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


ht.setDataAtCell(0, 0, 'new value');
Run Code Online (Sandbox Code Playgroud)

蒂姆,谢谢

Tan*_*ivy 7

如果您尝试访问核心方法,例如'setDataAtCell()',则可以使用refs来访问它们.

例如,将"ref ='xyz'"属性添加到HTML元素,然后可以使用"this.refs.xyz"调用它.我在下面修改了你的例子来说明.它添加了一个按钮,onClick将函数运行到'setDataAtCell'.

// import React...
import React from 'react';
import ReactDOM from 'react-dom';

// ... Handsontable with its main dependencies...
import moment from 'moment';
import numbro from 'numbro';
import pikaday from 'pikaday';
import Zeroclipboard from 'zeroclipboard';
import Handsontable from 'handsontable';

// ... and HotTable
import HotTable from 'react-handsontable';

class ExampleComponent extends React.Component {
  constructor(props) {
    super(props);
    this.handsontableData = [
      ["", "Ford", "Volvo", "Toyota", "Honda"],
      ["2016", 10, 11, 12, 13],
      ["2017", 20, 11, 14, 13],
      ["2018", 30, 15, 12, 13]
    ];
  }

  handleClick(e) {
    this.refs.hot.hotInstance.setDataAtCell(0, 0, 'new value')
  }

  render() {
    return (
      <div id="example-component">
        <HotTable root="hot"
                  data={this.handsontableData}
                  colHeaders={true}
                  rowHeaders={true}
                  width="600"
                  height="300"
                  stretchH="all"
                  ref="hot"
        />
        <br/>
        <button onClick={(e)=>this.handleClick(e)}>Click Me</button>
      </div>
    );
  }
}

export default ExampleComponent
Run Code Online (Sandbox Code Playgroud)

此方法可用于访问其他方法,如"getData()",可用于获取表中数据的快照,该快照可以保存到状态或类似状态.所以它比"ht"更长,你可以使用"this.refs.hot.hotInstance"来获得类似的效果.

您可以在React文档中的" Refs and the DOM "中阅读有关ref属性的更多信息.

  • 谢谢,这对我有用,但React现在建议使用[`createRef` API](https://reactjs.org/docs/refs-and-the-dom.html#creating-refs)而不是使用`this.直接引用([更多信息](https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs)). (2认同)