Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to make Table components possible

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "how to make Table components infinitely possible", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to make Table components infinitely possible.

Technical realization

1. Realize Table dynamic rendering

In general, when we render a table, most of the table structure is written in advance, rather than defining the columns first and then requesting the data to fill the table from the backend, as follows:

Const columns = [{title: 'name', dataIndex: 'name', key:' name',}, {title: 'age', dataIndex: 'age', key:' age',}, {title: 'address', dataIndex: 'address', key:' address',},] Const dataSource = [{key: '1Qing, name:' Xu Xiaoxi', age: 18, address: 'Hangzhou Xihu District',}]

Although this kind of business scenario can meet the Table requirements of most background management systems, and can also be built with antd or element, for lowcode systems, many modules are uncertain, and we need to drive Table rendering according to protocols and data.

For example, if we configure a form in H5-Dooring, we need to analyze the data of the form. Because the form items are uncertain, we cannot define a table schema in advance.

So how to render this Table dynamically? Here to provide you with an idea, based on data-driven + protocol layer constraints. Similar to the low code platform of foreign SAP, based on odata protocol, we can constrain the data format of the form submission, and then combine the data submitted by users to dynamically extract the columns needed for Table, and finally render the Table component.

The protocol layer mainly restricts the display types of different fields, such as strings, buttons, links, labels, etc. After submitting the form, users will bring the flag corresponding to the protocol layer and the values entered by the user, which helps our parser to display different types for different columns when rendering Table. It is as follows:

The author simply implements a demo here, as follows:

/ / table data source let tableData = res.map ((item:any,i:number) = > ({ID: nanoid (8),... item}); let baseRow = tableData [0], keys = Object.keys (baseRow) SetColumns (() = > {const baseColumn = keys.map (item = > {return {title: item, dataIndex: item, key: item, width: item = = 'ID'? 0: null Render: (v:any) = > {if (typeof v = 'object') {return {v.map (item = > {item.label | | item})} return item =' ID'?': v}) baseColumn.push ({title: 'Operation' Key: 'operation', fixed:' right', width: 100, render: (row) = > handleDel (row)} > delete,}) return baseColumn})

We have implemented a dynamic Table rendering scheme above. React is used in the case, and you can also use the familiar vue3.0.

2. Table sorting, multi-column sorting, custom search

Table sorting, multi-column sorting is also very simple. We only need to customize the Table header, upgrade the sorting field to the common State of Table, and finally sort through sorting identification and sorting methods. Currently, antd4.0 supports multi-column sorting. You can refer to the study directly, as follows:

For custom search, that is, the column search shown in demo at the beginning of the article, we can use the following solution:

Const getColumnSearchProps = dataIndex = > ({filterDropdown: ({setSelectedKeys, selectedKeys, confirm, clearFilters}) = > ({searchInput = node;}} placeholder= {`Search ${dataIndex} `} value= {selectedKeys [0]} onChange= {e = > setSelectedKeys (e.target.value? [e.target.value]: [])} onPressEnter= {() = > handleSearch (selectedKeys, confirm, dataIndex)} style= {{width: 188, marginBottom: 8, display: 'block'}} / > handleSearch (selectedKeys, confirm) DataIndex)} icon= {} size= "small" style= {{width: 90}} > search handleReset (clearFilters)} size= "small" style= {{width: 90}} > reset), filterIcon: filtered = >, onFilter: (value, record) = > record [dataIndex]? ToLowerCase [dataIndex] .toString (). Includes (value.toLowerCase ()):', onFilterDropdownVisibleChange: visible = > {if (visible) {setTimeout (() = > searchInput.select (), 100);}}, render: text = > searchedColumn = dataIndex? (): (text),})

At this point, we only need to add a custom header to each column of the dynamically generated columns:

{title: item, dataIndex: item, key: item,... getColumnSearchProps (item)}

There are also detailed ways to use antd4.0, so I won't introduce them here. The results are as follows:

You can also check the specific results in the management background of H5-Dooring.

3. Batch import Excel data rendering Table

In many data analysis backstage, we need to deal with a lot of spreadsheets, and the traditional manual input method of excel will be gradually eliminated. For example, different channels have collected a lot of business data and sorted it into excel, so how to quickly save it to their own background system? The general ideas are as follows:

Enter one by one through the form

The background parsing file is processed into a standard data structure that can be stored in the database.

The front end implements an import into excel to automatically synchronize data.

The first scheme is too inefficient and suitable for C-end users to enter manually. We ignore it for the time being. The author will implement the third scheme. The idea of implementation is as follows:

Here we use the library XLSX, combined with FileReader API. We get the binary data of excel file through FileReader, then send it to XLSX to parse it into js object, and finally generate a table data structure that conforms to the specification through the table renderer written by the author. The source code is as follows

/ / parse and extract excel data let reader = new FileReader (); reader.onload = function (e) {let data = e.target.result; let workbook = XLSX.read (data, {type: 'binary'}); let sheetNames = workbook.SheetNames; / / worksheet name collection let draftArr = {} sheetNames.forEach (name = > {let worksheet = workbook.Sheets [name]) / / you can only get the specified worksheet for (let key in worksheet) {/ / v is the original value of the read cell if (key [0]! ='!') {if (draftArr [key [0]]) {draftArr [key [0]] .push (worksheet [key] .v)} else {draftArr [ Key [0]] = [worksheet [key] .v]}) / / get the data product of table method: const sourceData = Object.values (draftArr);} reader.readAsBinaryString (file)

Once we have the legitimate table data source, we can proceed with the logic of dynamic rendering of Table in the first section.

Through the above way, we can achieve any structure of the excel table import. After import, we can automatically send requests to our business background.

4. Export Table data to Excel

Similarly, we introduced the import of excel into table, and we can also export Table to excel for data distribution and localization, such as our recently popular online documents and other applications. The author will briefly talk about the implementation ideas here:

This is what we call anti-parsing in section 3. The author uses the library js-export-excel to generate excel files. Based on it, the author implements an out-of-the-box method to avoid brain-burning wheels. It is as follows:

Import ExportJsonExcel from 'js-export-excel'; const generateExcel = () = > {let option:any = {}; / / option represents the excel file let dataTable = []; / / the data content in the excel file let len = list.length; if (len) {for (let iTuno; I (typeof item =' object'? Item.label: item) .join (',')} else {obj [key] = row [key]}} dataTable.push (obj); / / set the data source for each column in excel}} let tableKeys = Object.keys (dataTable [0]); option.fileName = tableName / / excel file name option.datas = [{sheetData: dataTable, / / data source in the excel file sheetName: tableName, / / sheet page name in the excel file sheetFilter: tableKeys, / / column data to be displayed in the excel file sheetHeader: tableKeys / / header name of each column in excel file}] let toExcel = new ExportJsonExcel (option) / / generate excel file toExcel.saveExcel (); / / download excel file}

5. Automatically generate Multi-dimensional Visualization report based on Table data

In the background management system and BI platform, we will encounter a lot of requirements for data analysis and report display. Next, the author will introduce how to dynamically generate multi-dimensional visual analysis reports based on Table data.

In the previous article, the author introduced the concept of measurement line. For data analysis, we should also consider the concept of analysizable dimension, such as what is analyzable and what is not. For example, we have another table with the following structure:

For contact information, it is immeasurable, that is, analyzing this item does not have any value, so we should not analyze it in theory in the automatic generation of multi-dimensional analysis. Based on this principle, let's design a simple scheme to automatically generate multi-dimensional visual reports.

5.1 obtaining dimensional data based on data source

We measure the dimensions with scope attributes and generate measurement data as follows:

Const generateDistData = (key:string, list:any) = > {let distDataMap:any = {}, distData = [] list.forEach ((item:any) = > {/ / current latitude category let curKey = typeof item [key] = 'object'? Item [key] [0] .label: item [key]; if (distDataMap [curkey]) {distDataMap [curkey] +;} else {distDataMap [curkey] = 1;}}) / / generate the target array for (let key in distDataMap) {distData.push ({name: key, value: distDataMap [curkey]})} return distData}

At this time, we only need to obtain the data value of a dimension according to the field of the dimension, and then render it through the visual component.

5.2 generate visual reports based on a certain dimension

We use @ ant-design/charts with the following code:

Analysis latitude: handleAnazlyChange (0, v)} defaultValue= {keys [0]} > {keys.map ((item,i) = > {return {item}})} {! config & &}

The results are as follows:

6. Implement a simple Table editor

To implement the Table editor, the author has analyzed in detail how to generate visual analysis reports for multi-dimensional data at the front end with one click, and is also integrated into the visual component editor of H5-Dooring. The specific demo is as follows:

At this point, I believe you have a deeper understanding of "how to make Table components infinitely possible". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report