欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ant table 扩展 显示html文档 格式化json字符串 并且 实时动态关键字高亮

程序员文章站 2022-04-24 07:53:29
...
环境 node react ant
问题:查看log存储信息,返回log中的报文 字段 显示 利于人浏览 (报文字段本身是json格式的字符串)

开发样例:

后台返回数据,table显示,大字段expandedRowRender处理,以html方式插入渲染大字段标签。
大字段json需要格式化后显示出来,并求大字段关键字查询后显示时高亮关键字。并且动态实时关键字高亮

数据显示在ant 的table中,使用扩展显示。如图

ant table 扩展 显示html文档 格式化json字符串 并且 实时动态关键字高亮



思路,首先如果格式化json后输出到界面 就要处理json字符串 ,添加 html 标签 回车(</br>) 空格(<&sbpn;>)替换,所以最后添加到页面的一定是能处理html的方式。
第一步:以html形式插入到table扩展位置 
请查看本人博文 React dangerouslySetInnerHTML - 将HTML字符串解析为html样式显示在table的扩展中



第二步.格式化json字符串添加 回车和空格的html,如下为方法功能(结合网上总结后修改的方法)


function jsonFormat(format){
	let msg='', pos = 0,  prevChar = '', outOfQuotes = true;
         for (let i = 0; i < format.length; i++) { //循环每一个字符
            let char = format.substring(i, i + 1);  //获取到该字符
            if (char == '"' && prevChar != '\\') {  //如果转移
                outOfQuotes = !outOfQuotes;         
            } else if ((char == '}' || char == ']') && outOfQuotes) {   //如果是关闭
                msg += "<br/>";
                pos--;
                for (let j = 0; j < pos; j++) msg += '    ';
            }
            msg += char;
            if ((char == ',' || char == '{' || char == '[') && outOfQuotes) {
                msg += "<br/>";
                if (char == '{' || char == '[') pos++;
                for (let k = 0; k < pos; k++) msg += '    ';
            }
            prevChar = char;
         }
	retutn msg;
}





第三步:通过搜索报文关键字返回的报文数据 关键字加高亮 
js方法如下://js替换关键字加html标签
   
    function formatter(msg,src) {
        let result = msg;
        if(src !== null && src !==undefined && src !== '' ){
            result =  msg.replace( new RegExp(src,'gm'), "<span style='color: blue; font-weight: bold;'>"+src+"</span>"); //#99ffdd
        }
        return result;
    }




关键三步解决:拼装在一起。

jsx文件完整代码:

import React from "react";
import { Table, Button, Form, Input, message, Select } from "antd";
import auth from "../common/auth.jsx";
const createForm = Form.create;
const FormItem = Form.Item;


let columns = [
    {
        title: '日志ID',
        dataIndex: 'id'
    }, {
        title: '错误代码',
        dataIndex: 'errorCode'
    }, {
        title: '错误信息',
        dataIndex: 'errorMsg'
    }, {
        title: '系统时间',
        dataIndex: 'updateDate'
    }
];


function formatter(format,src) {
     
      let msg='', pos = 0,  prevChar = '', outOfQuotes = true;
         for (let i = 0; i < format.length; i++) { //循环每一个字符
            let char = format.substring(i, i + 1);  //获取到该字符
            if (char == '"' && prevChar != '\\') {  //如果转移
                outOfQuotes = !outOfQuotes;         
            } else if ((char == '}' || char == ']') && outOfQuotes) {   //如果是关闭
                msg += "<br/>";
                pos--;
                for (let j = 0; j < pos; j++) msg += '    ';
            }
            msg += char;
            if ((char == ',' || char == '{' || char == '[') && outOfQuotes) {
                msg += "<br/>";
                if (char == '{' || char == '[') pos++;
                for (let k = 0; k < pos; k++) msg += '    ';
            }
            prevChar = char;
         }
       // console.log(msg);
        let result = msg;
        if(src !== null && src !==undefined && src !== '' ){
            result =  msg.replace( new RegExp(src,'gm'), "<span style='color: blue; font-weight: bold;'>"+src+"</span>"); //#99ffdd
        }
        return result;
    }

class LogList extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            outputMsg: '',
            inputMsg: '',
            updateDate: '',
            errorCode: '',
            id: '',
            params: {},
            pagination: { pageSize: 10, showQuickJumper: true },
            loading: false,
            tableData: []
        };
    }


    showhtml(record) {
        let inp = formatter(record.inputMsg,this.state.inputMsg);
        let out = formatter(record.outputMsg,this.state.outputMsg); 
        let inputMsg = "<span style='color:blue;margin-left: -20px ;'>输入报文信息如下:</span></br><span style='margin: 0px 0px 0px;'>" + inp + "</span>";
        let outputMsg = "<span style='color:blue;margin-left: -20px ;'>输出报文信息如下:</span></br><span style='margin: 0px 0px 0px;'>" + out + "</span>";
        let html = { __html: inputMsg + "</br></br></br>" + outputMsg };
        return <div dangerouslySetInnerHTML={html}></div>;
    }

   




    handleChangeIdKeyword(e) {
        this.setState({
            id: e.target.value
        });
    }

    handleChangeUpdateDateKeyword(e) {
        this.setState({
            updateDate: e.target.value
        });
    }

    handleChangeInputMsgKeyword(e) {
        this.setState({
            inputMsg: e.target.value
        });
    }

    handleChangeOutputMsgKeyword(e) {
        this.setState({
            outputMsg: e.target.value
        });
    }

    handleChangeErrorCodeKeyword(e) {
        this.setState({
            errorCode: e.target.value
        });
    }

    /**
     * 表格表单查询
     * @return {[type]} [description]
     */
    handelBtnQuery() {
        let params = this.state.params;

        if (this.state.id !== null && this.state.id !== "") {
            params.id = this.state.id;
        } else {
            delete params.id;
        }

        if (this.state.errorCode !== null && this.state.errorCode !== "") {
            params.errorCode = this.state.errorCode;
        } else {
            delete params.updateDate;
        }

        if (this.state.updateDate !== null && this.state.updateDate !== "") {
            params.updateDate = this.state.updateDate;
        } else {
            delete params.updateDate;
        }

        if (this.state.inputMsg !== null && this.state.inputMsg !== "") {
            params.inputMsg = this.state.inputMsg;
        } else {
            delete params.inputMsg;
        }

        if (this.state.outputMsg !== null && this.state.outputMsg !== "") {
            params.outputMsg = this.state.outputMsg;
        } else {
            delete params.outputMsg;
        }


        this.fetch(params);
    }




    /**
     * 调用后台服务
     *
     * @param params 传递给后台的参数
     */
    fetch(params = {}) {

        this.setState({ params: params, loading: true });

        auth.fetch('/log/getloglist', params, (res) => {

            this.setState({ loading: false });

            if (res.result == "0") {
                // if (res.data.list !== undefined && res.data.list.length > 0) {
                //     let list_length = res.data.list.length;
                //     for(var i=0; i<list_length; i++) {

                //      }
                //  }

                this.setState({
                    tableData: res.data.list,
                    pagination: {
                        total: res.data.total
                    }
                });
            } else {
                message.error(res.msg, 10);
            }
        });
    }

    componentDidMount() { //初始化
        this.fetch();
    }

    render() {


        return (
            <div>
                <div className="form-query">
                    <Form onSubmit={this.handleSubmit} layout="inline">
                        <FormItem label="日志ID">
                            <Input placeholder="请输入搜索的日志ID" ref="id" size="default" onChange={this.handleChangeIdKeyword.bind(this)} />
                        </FormItem>
                        <FormItem label="错误代码">
                            <Input placeholder="请输入错误代码" ref="errorCode" size="default" onChange={this.handleChangeErrorCodeKeyword.bind(this)} />
                        </FormItem>
                        <FormItem label="错误代码">
                            <Input placeholder="请输入错误时间" ref="updateDate" size="default" onChange={this.handleChangeUpdateDateKeyword.bind(this)} />
                        </FormItem>
                        <FormItem label="输入报文">
                            <Input placeholder="请输入报文连续片段" ref="inoutMsg" size="default" onChange={this.handleChangeInputMsgKeyword.bind(this)} />
                        </FormItem>
                        <FormItem label="输出报文">
                            <Input placeholder="请输入报文连续片段" ref="outputMsg" size="default" onChange={this.handleChangeOutputMsgKeyword.bind(this)} />
                        </FormItem>

                        <Button type="primary" onClick={this.handelBtnQuery.bind(this)}>查询</Button>
                    </Form>
                </div>

                <br />

                <Table columns={columns} rowKey={record => record.id}
                    dataSource={this.state.tableData}
                    pagination={this.state.pagination} loading={this.state.loading}
                    expandedRowRender={this.showhtml.bind(this)}
                />


            </div>
        );
    }




}

const loglist = createForm()(LogList);
export default loglist;



相关标签: 格式化 json