react中代码块输出,代码高亮显示,带行号,能复制

以modal组件为例:


import React, { useState, useEffect } from 'react';
import { Modal, Button, message } from 'antd';
import Highlight from 'react-highlight';
import "highlight.js/styles/mono-blue.css";
import { CopyToClipboard } from 'react-copy-to-clipboard';
import "./infoModal.less";
import hljs from 'highlight.js';

export default function infoModal(props: any) {
  const { visible, handleCancel, handleOk, modalType } = props;
  const [title, setIitle] = useState('');
  const [num, setNum] = useState(0);
  const [data, setData] = useState({
    "a": title,
    "a2": "1",
    "a3": "1",
    "a4": "1",
    "a5": "1",
    "a6": "1",
    "a7": "1",
    "a8": "1",
    "a9": "1",
  });



  useEffect(() => {
    if (modalType === "in") { setIitle("入参信息") } else { setIitle("出参信息") };
  }, [modalType]);

  //显示行号
  useEffect(() => {
    if (visible) {
      hljs.initHighlightingOnLoad();
      document.querySelectorAll('pre code').forEach((block) => {
        block.innerHTML = "<ul id='ulcode'><li>" + block.innerHTML.replace(/\n/g, "\n</li><li>") + " </li></ul>";
      });
    }
  }, [visible])

  const handleCopy = () => {
    message.success('复制成功!')
  };

  return <div>
    <Modal title={title} visible={visible} onCancel={handleCancel} onOk={handleOk}
      footer={[
        <CopyToClipboard text={JSON.stringify(data, null, 2)} onCopy={handleCopy}>
          <Button>复制</Button>
        </CopyToClipboard>,
        <Button key="submit" type="primary" onClick={handleCancel}>确定</Button>
      ]}
    >
      <Highlight className="javascript mycode" >
        {JSON.stringify(data, null, 2)}
      </Highlight>
    </Modal>
  </div>;
}

infoModal.less样式:

.hljs ul {			
  list-style: decimal;			
  margin: 0 0 0 40px!important;			
  padding: 0			
  }			
  .hljs li {			
  list-style: decimal-leading-zero;			
  border-left: 1px solid #333!important;			
  padding: 2px 5px!important;			
  margin: 0!important;			
  line-height: 14px;			
  width: 100%;			
  box-sizing: border-box
  }
  .hljs li:nth-of-type(even) {
  background-color: rgba(255,255,255,.015);
  color: inherit
  }


  .javascript{
    max-height:400px;
  }

效果图:

代码块显示:react-highlight插件

代码块复制:react-copy-to-clipboard插件

代码块显示行号:highlight.js插件+js代码(上文中已注释)+less样式(上文中已添加)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值