基於jsoneditor二次封裝一個可實時預覽的json編輯器組件react版

2020-12-22 酷扯兒

本文轉載自【微信公眾號:趣談前端,ID:beautifulFront】經微信公眾號授權轉載,如需轉載與原文作者聯繫

前言

做為一名前端開發人員,掌握vue/react/angular等框架已經是必不可少的技能了,我們都知道,vue或react等MVVM框架提倡組件化開發,這樣一方面可以提高組件復用性和可擴展性,另一方面也帶來了項目開發的靈活性和可維護,方便多人開發協作.接下來文章將介紹如何使用react,開發一個自定義json編輯器組件.我們這裡使用了jsoneditor這個第三方庫,官方地址: jsoneditor 通過實現一個json在線編輯器,來學習如何一步步封裝自己的組件(不限於react,vue,原理類似).

你將學到:

react組件封裝的基本思路SOLID (面向對象設計)原則介紹jsoneditor用法使用PropTypes做組件類型檢查設計思路

在介紹組件設計思路之前,有必要介紹一下著名的SOLID原則.

SOLID(單一功能、開閉原則、裡氏替換、接口隔離以及依賴反轉)是由羅伯特·C·馬丁提出的面向對象編程和面向對象設計的五個基本原則。利用這些原則,程式設計師能更容易和高效的開發一個可維護和擴展的系統。SOLID被典型的應用在測試驅動開發上,並且是敏捷開發以及自適應軟體開發的基本原則的重要組成部分。

S 單一功能原則: 規定每個類都應該有一個單一的功能,並且該功能應該由這個類完全封裝起來。所有它的服務都應該嚴密的和該功能保持一致。O 開閉原則: 規定「軟體中的對象(類,模塊,函數等等)應該對於擴展是開放的,但是對於修改是封閉的」,這意味著一個實體是允許在不改變它的原始碼的前提下變更它的行為。遵循這種原則的代碼在擴展時並不需要改變。L 裡氏替換原則: 派生類(子類)對象可以在程序中代替其基類(超類)對象,是對子類型的特別定義.I 接口隔離原則: 指明應用或者對象應該不依賴於它不使用的方法。接口隔離原則(ISP)拆分非常龐大臃腫的接口成為更小的和更具體的接口,這樣應用或對象只需要知道它們感興趣的方法。這種縮小的接口也被稱為角色接口。接口隔離原則(ISP)的目的是系統去耦合,從而容易重構,更改和重新部署。接口隔離原則是在SOLID (面向對象設計)中五個面向對象設計(OOD)的原則之一,類似於在GRASP (面向對象設計)中的高內聚性。D 依賴反轉原則: 是指一種特定的解耦 形式,使得高層次的模塊不依賴於低層次的模塊的實現細節,依賴關係被顛倒(反轉),從而使得低層次模塊依賴於高層次模塊的需求抽象。掌握好這5個原則將有利於我們開發出更優秀的組件,請默默記住.接下來我們來看看json編輯器的設計思路.

如上所示, 和任何一個輸入框一樣, 參考antd組件設計方式併兼容antd的form表單, 我們提供了onChange方法.(具體細節下文會詳細介紹)

首先利用jsoneditor渲染的基本樣式以及API,我們能實現一個基本可用的json編輯器,然後通過對外暴露的json和onChange屬性進行數據雙向綁定, 通過onError來監控異常或者輸入的錯誤, 通過themeBgColor來修改默認的主題色,通過這幾個接口,我們便能完全掌握一個組件的運行情況.

正文

接下來我們就正式開始我們的正文.由於本文的組件是基於react實現的,但是用在vue,angular上,基本模式同樣適用.關鍵就是掌握好不同框架的生命周期.

在學習實現json編輯器組件之前,我們有必要了解一下jsoneditor這個第三方組件的用法與api.

1. jsoneditor的使用

我們先執行npm install安裝我們的組件

npm install jsoneditor

其次手動引入樣式文件

<link href="jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">

這樣,我們就能使用它的api了:

<div id="jsoneditor" style="width: 400px; height: 400px;"></div><script>// 創建編輯器 var container = document.getElementById("jsoneditor"); var editor = new JSONEditor(container); // 設置json數據 function setJSON () { var json = { "Array": [1, 2, 3], "Boolean": true, "Null": null, "Number": 123, "Object": {"a": "b", "c": "d"}, "String": "Hello World" }; editor.set(json); } // 獲取json數據 function getJSON() { var json = editor.get(); alert(JSON.stringify(json, null, 2)); }</script>

所以你可能看到如下界面:

為了能實現實時預覽和編輯,光這樣還遠遠不夠,我們還需要進行額外的處理.我們需要用到jsoneditor其他的api和技巧.

2. 結合react進行二次封裝

基於以上談論,我們很容易將編輯器封裝成react組件, 我們只需要在componentDidMount生命周期裡初始化實例即可.react代碼可能是這樣的:

import React, { PureComponent } from 'react'import JSONEditor from 'jsoneditor'import 'jsoneditor/dist/jsoneditor.css'class JsonEditor extends PureComponent {initJsonEditor = () => { const options = { mode: 'code', history: true, onChange: this.onChange, onValidationError: this.onError }; this.jsoneditor = new JSONEditor(this.container, options) this.jsoneditor.set(this.props.value) } componentDidMount () { this.initJsonEditor() } componentWillUnmount () { if (this.jsoneditor) { this.jsoneditor.destroy() } } render() { return <div className="jsoneditor-react-container" ref={elem => this.container = elem} /> }}export default JsonEditor

至於options裡的選項, 我們可以參考jsoneditor的API文檔,裡面寫的很詳細, 通過以上代碼,我們便可以實現一個基本的react版的json編輯器組件.接下來我們來按照設計思路一步步實現可實時預覽的json編輯器組件.

3. 實現預覽和編輯視圖

其實這一點很好實現,我們只需要實例化2個編輯器實例,一個用於預覽,一個用於編輯就好了.

import React, { PureComponent } from 'react'import JSONEditor from 'jsoneditor'import 'jsoneditor/dist/jsoneditor.css'class JsonEditor extends PureComponent {onChange = () => { let value = this.jsoneditor.get() this.viewJsoneditor.set(value) } initJsonEditor = () => { const options = { mode: 'code', history: true }; this.jsoneditor = new JSONEditor(this.container, options) this.jsoneditor.set(this.props.value) } initViewJsonEditor = () => { const options = { mode: 'view' }; this.viewJsoneditor = new JSONEditor(this.viewContainer, options) this.viewJsoneditor.set(this.props.value) } componentDidMount () { this.initJsonEditor() this.initViewJsonEditor() } componentDidUpdate() { if(this.jsoneditor) { this.jsoneditor.update(this.props.value) this.viewJsoneditor.update(this.props.value) } } render() { return ( <div className="jsonEditWrap"> <div className="jsoneditor-react-container" ref={elem => this.container = elem} /> <div className="jsoneditor-react-container" ref={elem => this.viewContainer = elem} /> </div> ); }}export default JsonEditor

這樣,我們便能實現一個初步的可實時預覽的編輯器.可能效果長這樣:

接近於成熟版,但是還有很多細節要處理.

4. 對外暴露屬性和方法以支持不同場景的需要

import React, { PureComponent } from 'react'import JSONEditor from 'jsoneditor'import 'jsoneditor/dist/jsoneditor.css'class JsonEditor extends PureComponent {// 監聽輸入值的變化 onChange = () => { let value = this.jsoneditor.get() this.props.onChange && this.props.onChange(value) this.viewJsoneditor.set(value) } // 對外暴露獲取編輯器的json數據 getJson = () => { this.props.getJson && this.props.getJson(this.jsoneditor.get()) } // 對外提交錯誤信息 onError = (errArr) => { this.props.onError && this.props.onError(errArr) } initJsonEditor = () => { const options = { mode: 'code', history: true, onChange: this.onChange, onValidationError: this.onError }; this.jsoneditor = new JSONEditor(this.container, options) this.jsoneditor.set(this.props.value) } initViewJsonEditor = () => { const options = { mode: 'view' }; this.viewJsoneditor = new JSONEditor(this.viewContainer, options) this.viewJsoneditor.set(this.props.value) } componentDidMount () { this.initJsonEditor() this.initViewJsonEditor() // 設置主題色 this.container.querySelector('.jsoneditor-menu').style.backgroundColor = this.props.themeBgColor this.container.querySelector('.jsoneditor').style.border = `thin solid ${this.props.themeBgColor}` this.viewContainer.querySelector('.jsoneditor-menu').style.backgroundColor = this.props.themeBgColor this.viewContainer.querySelector('.jsoneditor').style.border = `thin solid ${this.props.themeBgColor}` } componentDidUpdate() { if(this.jsoneditor) { this.jsoneditor.update(this.props.value) this.viewJsoneditor.update(this.props.value) } } render() { return ( <div className="jsonEditWrap"> <div className="jsoneditor-react-container" ref={elem => this.container = elem} /> <div className="jsoneditor-react-container" ref={elem => this.viewContainer = elem} /> </div> ); }}export default JsonEditor

通過以上的過程,我們已經完成一大半工作了,剩下的細節和優化工作,比如組件卸載時如何卸載實例, 對組件進行類型檢測等,我們繼續完成以上問題.

5. 使用PropTypes進行類型檢測以及在組件卸載時清除實例

類型檢測時react內部支持的,安裝react的時候會自動幫我們安裝PropTypes,具體用法可參考官網地址propTypes文檔,其次我們會在react的componentWillUnmount生命周期中清除編輯器的實例以釋放內存.完整代碼如下:

import React, { PureComponent } from 'react'import JSONEditor from 'jsoneditor'import PropTypes from 'prop-types'import 'jsoneditor/dist/jsoneditor.css'/*** JsonEditor * @param {object} json 用於綁定的json數據 * @param {func} onChange 變化時的回調 * @param {func} getJson 為外部提供回去json的方法 * @param {func} onError 為外部提供json格式錯誤的回調 * @param {string} themeBgColor 為外部暴露修改主題色 */class JsonEditor extends PureComponent { onChange = () => { let value = this.jsoneditor.get() this.props.onChange && this.props.onChange(value) this.viewJsoneditor.set(value) } getJson = () => { this.props.getJson && this.props.getJson(this.jsoneditor.get()) } onError = (errArr) => { this.props.onError && this.props.onError(errArr) } initJsonEditor = () => { const options = { mode: 'code', history: true, onChange: this.onChange, onValidationError: this.onError }; this.jsoneditor = new JSONEditor(this.container, options) this.jsoneditor.set(this.props.value) } initViewJsonEditor = () => { const options = { mode: 'view' }; this.viewJsoneditor = new JSONEditor(this.viewContainer, options) this.viewJsoneditor.set(this.props.value) } componentDidMount () { this.initJsonEditor() this.initViewJsonEditor() // 設置主題色 this.container.querySelector('.jsoneditor-menu').style.backgroundColor = this.props.themeBgColor this.container.querySelector('.jsoneditor').style.border = `thin solid ${this.props.themeBgColor}` this.viewContainer.querySelector('.jsoneditor-menu').style.backgroundColor = this.props.themeBgColor this.viewContainer.querySelector('.jsoneditor').style.border = `thin solid ${this.props.themeBgColor}` } componentWillUnmount () { if (this.jsoneditor) { this.jsoneditor.destroy() this.viewJsoneditor.destroy() } } componentDidUpdate() { if(this.jsoneditor) { this.jsoneditor.update(this.props.value) this.viewJsoneditor.update(this.props.value) } } render() { return ( <div className="jsonEditWrap"> <div className="jsoneditor-react-container" ref={elem => this.container = elem} /> <div className="jsoneditor-react-container" ref={elem => this.viewContainer = elem} /> </div> ); }}JsonEditor.propTypes = { json: PropTypes.object, onChange: PropTypes.func, getJson: PropTypes.func, onError: PropTypes.func, themeBgColor: PropTypes.string}export default JsonEditor

由於組件嚴格遵守開閉原則,所以我們可以提供更加定製的功能在我們的json編輯器中,已實現不同項目的需求.對於組件開發的健壯性探討,除了使用propTypes外還可以基於typescript開發,這樣適合團隊開發組件庫或者複雜項目組件的追溯和查錯.

相關焦點

  • 精通React/Vue系列之帶你實現一個功能強大的通知提醒框
    正文在開始組件設計之前希望大家對css3和js有一定的基礎,並了解基本的react/vue語法.我們先來解構一下Notification組件, 一個Notification分為以下幾個部分:每一個區塊都可以自定義配置, 也可以組合其他組件.並且我們可以配置提醒框出現的位置,就像antd
  • 如何用純css打造類materialUI的按鈕點擊動畫並封裝成react組件
    上圖已經是筆者基於react封裝好的一個按鈕Button組件,那麼我們就先一步步實現它吧.組件設計思路僅僅用上述代碼雖然可以實現一個按鈕點擊的動畫效果,但是並不通用, 也不符合作為一個經驗豐富的程式設計師的風格,所以接下來我們要一步步把它封裝成一個通用的按鈕組件,讓它無所不用.
  • 打造一款基於monaco-editor及markdown-it的Markdown編輯器(上)
    ;基於騰訊云云開發 cloudBase 的圖片拖拽上傳功能;接下來我將針對 Monaco editor、 markdown-it 的使用以及相應功能點進行展開前期準備根據 Markdown 的基本布局,在 UI 層,我們將 Markdown 布局方面主要劃分為:菜單欄、編輯區、預覽區
  • 《精通react/vue組件設計》之快速實現一個可定製的進度條組件
    每一個組件只負責某一特定的表現或者功能)正文在開始組件設計之前希望大家對css3和js有一定的基礎.我們先看看實現後的組件效果:上圖可以知道封裝後的進度條組件通過對外暴露的接口(react/vue裡面可以看做
  • 一個在線css三角形生成器
    在線css三角形生成器預覽由預覽動畫我們可以看到通過在線工具我們可以輕鬆配置各種想要的三角形, 並且能實時查看css代碼. 開發完這個工具之後筆者再也不用擔心還需要手寫三角形代碼了.2.編輯器實現編輯器實現也是前端老生長談的話題了, 筆者在H5-Dooring項目中寫過一個非常複雜的編輯器, 但是這裡我們只要需要一個靜態且簡單的編輯器就夠了.
  • 輕鬆使用純css3打造有點意思的故障藝術(附React加強組件版)
    正文接下來筆者將帶大家使用純Css3來實現"故障動畫", 並將這一特效封裝成React/vue組件, 供大家學習和使用. 先來看看實現的效果:當然在下面的文章中筆者還會介紹其他風格的"故障動畫".所以在文章開頭的動畫實現就變得很簡單了,我們只需要設置一個畫布背景,然後用內容混合讓文字疊加, 最後設計文字和故障線的動畫即可. 接下來我們看看具體的實現步驟.實現方案我們先來實現文字的混合效果, 故障線和畫布背景, css代碼如下:.blink {// ...
  • 基於Vue實現一個有點意思的拼拼樂小遊戲
    技術棧如下:vue-cli4 基於vue的腳手架Xuery 筆者基於原生js二次封裝的dom庫vue mvvm庫因為該應用屬於H5遊戲,為了清亮化筆者沒有採用第三方ui庫, 如果大家想採用基於vue的第三方移動端ui庫,筆者推薦如下:Mint 餓了麼推出的移動端ui庫NutUI 一套京東風格的移動端組件庫muse-ui 基於MaterialUI風格的移動端UI組件cube-ui
  • 前端: 如何利用Qrcode製作一個二維碼生成器?
    效果預覽 QR Code數據表示方法 : 深色模塊表示二進位"1",淺色模塊表示二進位"0"。Qrcode基本使用記憶如何包裝成自定義受控組件因為我們大多數項目目前都採用react或者vue開發了, 所以我們直接用對應的插件版本即可, 這裡筆者使用的是qrcode.react.
  • 《精通react/vue組件設計》之實現一個健壯的警告提示(Alert)組件
    本文轉載自【微信公眾號:趣談前端,ID:beautifulFront】經微信公眾號授權轉載,如需轉載與原文作者聯繫前言本文是筆者寫組件設計的第七篇文章, 今天帶大家實現一個自帶主題且可關閉的Alert組件, 該組件在諸如Antd或者elementUI等第三方組件庫中都會出現,主要用來提供系統的用戶反饋
  • 精通react/vue組件設計教你實現一個極具創意的加載(Loading)組件
    本文轉載自【微信公眾號:趣談前端,ID:beautifulFront】經微信公眾號授權轉載,如需轉載與原文作者聯繫前言本文是筆者寫組件設計的第八篇文章, 今天帶大家用5分鐘實現一個極具創意的加載(loading)組件.涉及的核心知識點主要是css3相關特性, 如果大家非常熟悉,可直接跳過介紹直接看正文
  • 微信開發者工具更新:編輯器優化 清除訂閱消息授權數據
    據IT之家網友「stevapple」投稿,微信團隊消息,微信開發者工具穩定版 1.02.2003250 近日更新:雲開發支持按量付費、PC小程序調試、圖標更新等。  以下為官方更新公告:  1. 編輯器優化  微信開發者工具的編輯器功能經過重新調整,優化並增加了若干功能。
  • 純前端表格控制項 SpreadJS V14.0 發布:組件化編輯器+數據透視表
    Excel 高度兼容」的產品特性,可為用戶提供高度類似 Excel 的功能,滿足 Web Excel組件開發、 表格文檔協同編輯、 數據填報、 類Excel報表設計等業務場景需求,極大的降低企業的研發成本和項目交付風險。
  • JeecgBoot 2.4 微服務正式版發布,基於 SpringBoot 的低代碼平臺
    採用最新主流前後分離框架(SpringBoot+Mybatis-plus+Ant-Design+Vue),容易上手; 代碼生成器依賴性低,靈活的擴展能力,可靈活實現二次開發; 開發效率很高,採用代碼生成器,單表數據模型和一對多(父子表)、樹列表等數據模型,增刪改查功能自動生成,菜單配置直接使用(前端代碼和後端代碼都一鍵生成);
  • Cocos Creator 3.0 預覽版來襲 期待更強2D、3D技術
    近日,Cocos Creator 3.0 預覽版已經發布。該版本在功能上已經接近正式版,可以用於新項目立項和特性預研。Cocos Creator 3.0 集成了原有 2D 和 3D 兩套產品的所有功能,並在編輯器和引擎上做出多項更新。
  • Unity首次公開實時數字人類短片《異教徒》:電影大片般逼真
    Unity 2019.3版本帶來了超過260項功能改進,尤其是高清渲染管線(HDRP)可在高端遊戲主機、PC上呈現高清精美畫質,《異教徒》短片就是基於該技術製作中製作的。它將實時渲染技術充分應用到影視動畫製作之中,通過組合3D、4D掃描獲得的數據,創作出皺紋、毛孔等微觀表面細節驚人的「實時數字人類」,呈現近乎完美的高端視覺效果。
  • 秀米編輯器pc版下載
    秀米編輯器pc版下載簡介:秀米編輯器是一款比較知名的微信圖文編輯工具,內置超多圖片和文字素材,可以讓你的公眾號文章擺脫平庸,綻放更多的色彩。秀米編輯器界面簡約大氣,左側是素材選擇框,右側是預覽和編輯窗口,大家排版完畢後直接複製粘貼到微信公眾號後臺即可生效,只為生成專屬內容。
  • 支持鴻蒙 2.0 手機版,華為 DevEco Studio 2.0 Beta3 發布
    HarmonyOS 軟體包以 APP Pack(Application Package)形式發布,它是由一個或多個 HAP(HarmonyOS Ability Package)以及描述每個 HAP 屬性的 pack.info 組成。HAP 是 Ability 的部署包,HarmonyOS 應用代碼圍繞 Ability 組件展開。
  • 支持鴻蒙 HarmonyOS 2.0 手機版,華為 DevEco Studio 2.0 Beta3...
    HarmonyOS 軟體包以 APP Pack(Application Package)形式發布,它是由一個或多個 HAP(HarmonyOS Ability Package)以及描述每個 HAP 屬性的 pack.info 組成。HAP 是 Ability 的部署包,HarmonyOS 應用代碼圍繞 Ability 組件展開。
  • 基於SpringBoot+AntDesign 的快速開發平臺,JeecgBoot 2.0.2 版本...
    項目介紹Jeecg-Boot 是一款基於SpringBoot+代碼生成器的快速開發平臺!