react网格生成_如何在React中构建实时可编辑数据网格

本文介绍了如何使用react-table库和Hamoni Sync服务在React中构建一个实时可编辑的数据网格。通过react-table实现表格渲染,借助Hamoni Sync实现实时状态同步,确保更新在所有设备上即时生效。
摘要由CSDN通过智能技术生成

react网格生成

by Peter Mbanugo

彼得·姆巴努戈(Peter Mbanugo)

如何在React中构建实时可编辑数据网格 (How to Build a Real-time Editable Datagrid In React)

A datagrid enables you to display and edit data. This is a vital feature in most data-driven applications.

数据网格使您可以显示和编辑数据。 在大多数数据驱动的应用程序中,这是至关重要的功能。

You may have implemented this in one of your React apps in the past. Maybe you used libraries like react-bootstrap-table, react-grid, or react-table. With those, you can add a Datagrid to your React app. But what if you want the changes to be done in real-time and updates synchronized across all connected devices and their browsers?

您过去可能已经在您的一个React应用中实现了这一点。 也许您使用了诸如react-bootstrap-tablereact-gridreact-table之类的库 。 有了这些,您可以将Datagrid添加到您的React应用程序中。 但是,如果您希望实时进行更改并在所有连接的设备及其浏览器之间同步更新,该怎么办?

In this article, I will show you how to build a real-time datagrid in React using react-table and Hamoni Sync.

在本文中,我将向您展示如何使用react-tableHamoni Sync在React中构建实时数据网格。

react-table is a lightweight and fast library for rendering tables in React, and it supports pagination and many more features.

react-table是一个轻量级,快速的库,用于在React中渲染表,它支持分页和许多其他功能。

Hamoni Sync is a real-time state synchronization service which enables you to synchronize your application state in real-time. I will show you how to build a datagrid with people’s first and last names.

Hamoni Sync是一种实时状态同步服务,使您可以实时同步应用程序状态。 我将向您展示如何使用人们的名字和姓氏构建数据网格。

If you want to follow along, you should have some knowledge of React and have the following tools installed:

如果您想继续学习,那么您应该对React有所了解,并安装了以下工具:

  1. NodeJS

    节点JS

  2. npm & npx. If you have installed npm version 5.2.0 or greater, it installs npx alongside npm.

    npmnpx 。 如果您已安装npm 5.2.0或更高版本,它将与npm一起安装npx。

  3. create-react-app

    创建React应用

创建React应用 (Create the React app)

First we will create a new React project using create-react-app.

首先,我们将使用create-react-app创建一个新的React项目。

Open the command line and run npx create-react-app realtime-react-datatable. This will bootstrap a React application for us by creating a new directory realtime-react-datatable with the files needed to build a React application.

打开命令行并运行npx create-react-app realtime-react-datatable 。 这将通过使用构建React应用程序所需的文件创建一个新目录realtime-react-datatable为我们引导一个React应用程序。

With the React app created, we need to install react-table and Hamoni Sync. Still on the command line, run cd realtime-react-datatable to switch to the directory for the app. Run npm i react-table hamoni-sync in the command line to install both packages.

创建React应用程序后,我们需要安装react-table和Hamoni Sync。 仍然在命令行上,运行cd realtime-react-datatable切换到应用程序的目录。 在命令行中运行npm i react-table hamoni-sync以安装这两个软件包。

渲染数据网格 (Render the Datagrid)

To render the datagrid, we will use the react-table component. Open the file src/App.js and update it with the code below:

为了渲染数据网格,我们将使用react-table组件。 打开文件src/App.js并使用以下代码进行更新:

import React, { Component } from "react";import logo from "./logo.svg";import "./App.css";// Import React Tableimport ReactTable from "react-table";import "react-table/react-table.css";// Import Hamoni Syncimport Hamoni from "hamoni-sync";
class App extends Component {  constructor() {    super();    this.state = {      data: [],      firstName: "",      lastName: ""    };  }
handleChange = event => {    if (event.target.name === "firstName")      this.setState({ firstName: event.target.value });    if (event.target.name === "lastName")      this.setState({ lastName: event.target.value });  };
handleSubmit = event => {    event.preventDefault();  };
renderEditable = cellInfo => {    return (      <div        style={{ backgroundColor: "#fafafa" }}        contentEditable        suppressContentEditableWarning        onBlur={e => {          const data = [...this.state.data];          data[cellInfo.index][cellInfo.column.id] = e.target.innerHTML;          this.setState({ data });        }}        dangerouslySetInnerHTML={{          __html: this.state.data[cellInfo.index][cellInfo.column.id]        }}      />    );  };
render() {    const { data } = this.state;
return (      <div className="App">        <header className="App-header">          <img src={logo} className="App-logo" alt="logo" />          <h1 className="App-title">Welcome to React</h1>        </header>        <p className="App-intro">          <form onSubmit={this.handleSubmit}>            <h3>Add new record</h3>            <label>              FirstName:              <input                type="text"                name="firstName"                value={this.state.firstName}                onChange={this.handleChange}              />            </label>{" "}            <label>              LastName:              <input                type="text"                name="lastName"                value={this.state.lastName}                onChange={this.handleChange}              />            </label>
<input type="submit" value="Add" />          </form>        </p>        <div>          <ReactTable            data={data}            columns={[              {                Header: "First Name",                accessor: "firstName",                Cell: this.renderEditable              },              {                Header: "Last Name",                accessor: "lastName",                Cell: this.renderEditable              },              {                Header: "Full Name",                id: "full",                accessor: d => (                  <div                    dangerouslySetInnerHTML={{                      __html: d.firstName + " " + d.lastName                    }}                  />                )              }            ]}            defaultPageSize={10}            className="-striped -highlight"          />        </div>      </div>    );  }}
export default App;

The code above renders a form and an editable react-table component. <ReactTable /> renders a component with data, columns, and defaultPageSize props. The data props holds the data to display, and columns props for the column definition. The accessor property in columns props indicates the property that holds the value to be displayed for that column. Cell: this.renderEditable property in columns props tells react-table that the column is editable. The other functions (handleSubmit & handleChange) allows getting new data entry from the form on the page.

上面的代码呈现了一个表单和一个可编辑的react-table组件。 <ReactTable />呈现组件wit ħ data, c olumns , and defaultPa geSize道具. Th . Th Ë数据道具保存数据到显示, and c olumns道具列定义. The ac . The ac cessor适当ty in c olumns道具指示保存要显示的是合作和属性值lumn. Cell: this.renderEd lumn. Cell: this.renderEd ty in c列道具ty in c this.renderEd可设置属性告诉react-table该列是可编辑的。 其他功能ions (handle mit & handle更改)允许从页面上的表单获取新数据。

添加Hamoni Sync (Add Hamoni Sync)

The data for the datagrid will be retrieved and updated in real-time using Hamoni Sync. We already imported the Hamoni library on line 18 in App.js;

数据网格的数据将使用Hamoni Sync进行实时检索和更新。 我们已经在App.js第18行中导入了App.js库;

import Hamoni from "hamoni-sync";

We need to initialize it and connect to Hamoni server. To do this we need an account and application ID. Follow these steps to create an application in Hamoni.

我们需要初始化它并连接到Hamoni服务器。 为此,我们需要一个帐户和应用程序ID。 请按照以下步骤在Hamoni中创建一个应用程序。

  1. Register and login to Hamoni dashboard

    注册并登录Hamoni 仪表板

  2. Enter your preferred application name in the text field and click the create button. This should create the app and display it in the application list section.

    在文本字段中输入首选的应用程序名称,然后单击创建按钮。 这将创建该应用程序并将其显示在“应用程序列表”部分中。
  3. Click the button “Show AccountID” to see your account ID.

    单击按钮“显示帐户ID”以查看您的帐户ID。

Add the following code to App.js to initialise and connect to Hamoni Sync server.

将以下代码添加到App.js以初始化并连接到App.js Sync服务器。

componentDidMount() {    let hamoni = new Hamoni("ACCOUNT_ID", "APP_ID");
hamoni      .connect()      .then(() =>; {
})      .catch(console.log);  }

The code above will connect the client device or browser to Hamoni Sync server. Copy your account and application ID from the dashboard and replace them with the string placeholder respectively.

上面的代码会将客户端设备或浏览器连接到Hamoni Sync服务器。 从仪表板上复制您的帐户和应用程序ID,然后分别用字符串占位符替换它们。

Add the following to the function in the then() block, to be executed when it successfully connects to the server:

将以下内容添加到then()块中的函数中,以在成功连接到服务器时执行该函数:

hamoni    .get("datagrid")    .then(listPrimitive => {      this.listPrimitive = listPrimitive;
this.setState({        data: [...listPrimitive.getAll()]      });
listPrimitive.onItemAdded(item => {        this.setState({ data: [...this.state.data, item.value] });      });
listPrimitive.onItemUpdated(item => {        let data = [        ...this.state.data.slice(0, item.index),        item.value,        ...this.state.data.slice(item.index + 1)        ];
this.setState({ data: data });      });
listPrimitive.onSync(data => {        this.setState({ data: data });      });    })    .catch(console.log);

The code above calls hamoni.get("datagrid") to get the data, with datagrid as the name of the application state on Hamoni Sync. Hamoni Sync allows you to store 3 kinds of state referred to as Sync primitives. They are:

上面的代码调用hamoni.get("datagrid")来获取数据,其中datagrid作为Hamoni Sync上应用程序状态的名称。 Hamoni Sync允许您存储3种状态,称为“同步”原语。 他们是:

  1. Value Primitive: This kind of state holds simple information represented with datatypes like string, boolean or numbers. It is best suited for cases such as unread message count, toggles, etc.

    值原始值 :这种状态包含简单信息,这些信息用数据类型表示,例如字符串,布尔值或数字。 最适合未读消息计数,切换等情况。

  2. Object Primitive: Object state represents states that can be modeled as a JavaScript object. An example usage could be storing the score of a game.

    Object Primitive :对象状态表示可以建模为JavaScript对象的状态。 示例用法可以是存储游戏得分。

  3. List Primitive: This holds a list of state objects. A state object is a JavaScript object. You can update an item based on its index in the list.

    列表基元 :包含状态对象的列表。 状态对象是JavaScript对象。 您可以根据列表中的项目索引来更新项目。

If the state is available it resolves and returns a promise with the state primitive object. This object gives us access to methods to update state and get state updates in real-time.

如果状态可用,则解析并返回带有状态原始对象的promise。 该对象使我们可以访问更新状态并实时获取状态更新的方法。

On line 36 we used the getAll() method to get data and set the state for the React component. Also, the methods onItemAdded() and onItemUpdated() are used to get updates when an item is added or updated. The onSync() method is useful in a scenario where a device or browser loses connection, and when it reconnects, it tries to get the latest state from the server and update the local state if there's any.

在第36行,我们使用getAll()方法获取数据并设置React组件的状态。 另外,在添加或更新项目时,使用onItemAdded()onItemUpdated()方法获取更新。 onSync()方法在设备或浏览器失去连接,并且在重新连接时会尝试从服务器获取最新状态并更新本地状态(如果有)的情况下非常有用。

添加和更新项目 (Add & Update items)

From the previous section, we are able to get the data for the datagrid and update the state when an item is added or update. Let’s add code to add new items and update an item when a column has been edited. Add the following code to the handleSubmit method:

从上一节中,我们能够获取数据网格的数据并在添加或更新项目时更新状态。 让我们添加代码以添加新项目并在编辑列后更新项目。 将以下代码添加到handleSubmit方法中:

handleSubmit = event => {    this.listPrimitive.push({        firstName: this.state.firstName,        lastName: this.state.lastName    });    this.setState({ firstName: "", lastName: "" });    event.preventDefault();};

This code gets the first and last name from the form and adds it to the list state primitive on Hamoni Sync by calling the push() method. This will trigger the onItemAdded() method.

这段代码从表单中获取名字和姓氏,并通过调用push()方法将其添加到Hamoni Sync的列表状态原语中。 这将触发onItemAdded()方法。

In order to update items as they get edited in the datagrid, we will update the function passed to the onBlur props on line 84 as follows:

为了更新在数据网格中编辑的项目,我们将更新第84行传递给onBlur道具的函数,如下所示:

onBlur={e => {    let row = this.state.data[cellInfo.index];    row[cellInfo.column.id] = e.target.innerHTML;    this.listPrimitive.update(cellInfo.index, row);}}

This code updates the item at the index retrieved from the cellInfo object. To update a list state primitive in Hamoni Sync, you call the update()method with the index of the item and the value to update. The renderEditable method should now look like this after the last change:

此代码更新从cellInfo对象检索到的索引处的cellInfo 。 要在Hamoni Sync中更新列表状态原语,请调用带有项目索引和值的update()方法。 在最后一次更改之后, renderEditable方法现在应如下所示:

renderEditable = cellInfo => {    return (      <div        style={{ backgroundColor: "#fafafa" }}        contentEditable        suppressContentEditableWarning        onBlur={e => {          let row = this.state.data[cellInfo.index];          row[cellInfo.column.id] = e.target.innerHTML;          this.listPrimitive.update(cellInfo.index, row);        }}        dangerouslySetInnerHTML={{          __html: this.state.data[cellInfo.index][cellInfo.column.id]        }}      />    );  };

At this point we have almost all that’s needed to run the app except the initial data that will be rendered on the datagrid.

至此,除了将要在数据网格上呈现的初始数据外,我们几乎具有运行该应用程序所需的全部内容。

We need to create the state and give it some data on Hamoni Sync. Add a new file seed.js at the root of your working directory and add to it the following code:

我们需要创建状态,并在Hamoni Sync上为其提供一些数据。 在工作目录的根目录下添加一个新文件seed.js ,并添加以下代码:

const Hamoni = require("hamoni-sync");
let hamoni = new Hamoni("AccountID", "APP_ID");
hamoni  .connect()  .then(response => {    hamoni      .createList("datagrid", [        { firstName: "James", lastName: "Darwin" },        { firstName: "Jimmy", lastName: "August" }      ])      .then(() => console.log("create success"))      .catch(console.log);  })  .catch(console.log);

This will create a list primitive state on Hamoni Sync, with a name of datagrid. Replace the AccountID and APP_ID string with your account and application ID. Open the command line and run node seed.js. This should succeed and print out create success message.

这将在Hamoni Sync上创建一个名为datagrid的列表原始状态。 用您的帐户和应用程序ID替换AccountIDAPP_ID字符串。 打开命令行并运行node seed.js 这应该成功并打印出create success消息。

Now we can start the React app and see our app in action! Run the command npm start in the command line and it'll open the application in your default browser.

现在我们可以启动React应用程序,看看我们的应用程序正在运行! 在命令行中运行命令npm start ,它将在您的默认浏览器中打开该应用程序。

Hooray! We have a real-time editable datagrid with pagination!

万岁! 我们有一个带有分页功能的实时可编辑数据网格!

结论 (Conclusion)

We have built a real-time datagrid in React using react-table and Hamoni Sync. With react-table powering the datagrid and Hamoni Sync handling the state for the datagrid. This was all achieved in few lines of code and less effort designing real-time state logic. You can get the finished app of what we built on GitHub. It’s possible to track which cell is being edited or lock the cells currently being edited by another user. I’ll leave that as a weekend hack for you.

我们已经使用react-tableHamoni Sync在React中构建了一个实时数据网格。 通过React表为数据网格供电,并且Hamoni Sync处理数据网格的状态。 所有这些都可以通过几行代码和更少的精力来设计实时状态逻辑来实现。 您可以获取我们在GitHub上构建的应用程序的完整应用程序。 可以跟踪正在编辑哪个单元格,或者锁定另一个用户当前正在编辑的单元格。 我会将其作为周末的技巧留给您。

Feel free to leave a comment if anything is not clear or encounter problems while trying to add lock or highlight cells being edited.

如果有任何不清楚的地方或尝试添加锁定或突出显示正在编辑的单元格时遇到问题,请随时发表评论。

Happy coding ?

编码愉快吗?

翻译自: https://www.freecodecamp.org/news/how-to-build-a-real-time-editable-datagrid-in-react-c13a37b646ec/

react网格生成

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值