纯干货分享: 如何在 React 框架中使用 SpreadJS

发布时间:2018/05/23 14:05 发布者:葡萄城

返回博客中心

概述

SpreadJS 最好的功能之一就是能够在不同的框架中使用它。本文将演示如何在简单的 Web 页面中使用 Babel JavaScript 编译器将 SpreadJS 与 React 快速结合。

第1步:设置 HTML5 页面

首先,我们需要在页面中添加对React的引用:

 <!DOCTYPE html>
 <html>
 <head>
 <meta charset="UTF-8" />
 <title>SpreadJS React Demo</title>
 <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
 <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
 </head>
 </html>

在这个页面中,我们将使用 Babel 的预编译版本(称为 babel-standalone),因此我们也会添加一个对此的引用:

 <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

最后,添加对 Spread.Sheets 的引用:

 <script src="http://cdn.grapecity.com/spreadjs/hosted/scripts/gc.spread.sheets.all.11.0.0.min.js"></script>

<link rel="stylesheet" type="text/css" href="http://cdn.grapecity.com/spreadjs/hosted/css/gc.spread.sheets.excel2013white.11.0.0.css">
 

在我们编写任何脚本之前,我们需要定义一个 DIV 元素来包含 Spread 实例。我们称之为 “root”。

<div id="root"></div>

第2步:为 Spread.Sheets 创建一个 React 类

接下来,在页面中添加一个脚本元素。我们将把所有的代码放在这里:

 <script type="text/babel"></script>
 

然后,为 Spread.Sheets 定义一个 React 组件,以便我们可以定义一个扩展 React.Component 的类:

 class ReactSpreadJS extends React.Component{ 
 }
 

该类需要在其中定义 componentDidMount 和 render 函数。componentDidMount 函数在组件被挂载后立即被调用,所以我们用它来初始化 Spread 实例:

 componentDidMount() { 
 //In the DidMount life cycle, we initialize Spread Sheet instance, and the host is defined in the Component template. 
 let spread = new GC.Spread.Sheets.Workbook(this.refs.spreadJs, {sheetCount: 3}); 

if(this.props.workbookInitialized){ 
 this.props.workbookInitialized(spread); 
 }
 }

接下来,在渲染函数中定义 Spread.Sheets DOM 元素:

 render() { 
 //Define the Spread.Sheets DOM template 
 return( 
 <div ref="spreadJs"  style={{width:'100%',height:'100%'}}> 
 </div>); 
 } 

第3步:为组件创建一个应用程序类

首先,通过 App 类定义应用程序 React 组件:

 //Define the application react component. 
 class App extends React.Component{  } 
 

接下来,添加一个您将调用 ReactSpreadJS 组件的渲染函数:

 render(){ 
 //In the root component, it include one ReactSpreadJS component. 
 return( 
 <div style={{width:'800px',height:'600px'}}> 
 <ReactSpreadJS workbookInitialized = {(spread)=>{console.log(spread)}}> 

</ReactSpreadJS> 
 </div> 
 ) 
 } 

要完成脚本,请告诉 React 通过使用 ReactDOM.render 来初始化应用程序:

 ReactDOM.render( 
 //Main entry, initialize application react component.
 <App/>,
 document.getElementById('root')
 );
 

这就是使用 React 将 Spread.Sheets 添加到 HTML 页面所需的全部内容。这只是 React 和 Spread.Sheets 的基本使用,但可以轻松扩展。


SpreadJS | 下载试用

纯前端表格控件 SpreadJS,是市面上布局与功能都与 Excel 高度类似的一款表格控件,全中文操作界面,适用于 .NET、Java、移动端等多个平台的类 Excel 数据开发,备受华为、中通、民航飞行学院等国内知名企业客户青睐。

您对 SpreadJS 产品的任何技术问题,都有技术支持工程师提供 1 对 1 专业解答,点击此处即可发帖提问>>技术支持论坛


关于葡萄城

赋能开发者!葡萄城是专业的集开发工具、商业智能解决方案、低代码开发平台于一身的软件和服务提供商,为超过 75% 的全球财富 500 强企业提供服务。葡萄城专注控件软件领域30年,希望通过模块化的开发控件、灵活的低代码应用开发平台等一系列开发工具、解决方案和服务,帮助开发者快速响应复杂多变的业务需求,最大程度地发挥开发者的才智和潜能,让开发者的 IT 人生更从容更美好。

了解详情,请访问葡萄城官网