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

2020-12-23 酷扯兒

本文轉載自【微信公眾號:趣談前端,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組件,那麼我們就先一步步實現它吧.組件設計思路僅僅用上述代碼雖然可以實現一個按鈕點擊的動畫效果,但是並不通用, 也不符合作為一個經驗豐富的程式設計師的風格,所以接下來我們要一步步把它封裝成一個通用的按鈕組件,讓它無所不用.
  • 十大最受歡迎的 React Native 應用開發編輯器
    它有一個龐大而活躍的社區,誕生了很多有用的插件。Atom 常用的包atom-react-native-autocomplete package - 該包針對 React-Native,為 Atom 編輯器提供自動補全功能。atom-react-native-css - 這是一個內置支持 SASS、SCSS 的 React-Native 組件的包。
  • 打造一款基於monaco-editor及markdown-it的Markdown編輯器(上)
    ;基於騰訊云云開發 cloudBase 的圖片拖拽上傳功能;接下來我將針對 Monaco editor、 markdown-it 的使用以及相應功能點進行展開前期準備根據 Markdown 的基本布局,在 UI 層,我們將 Markdown 布局方面主要劃分為:菜單欄、編輯區、預覽區
  • 一個在線css三角形生成器
    在線css三角形生成器預覽由預覽動畫我們可以看到通過在線工具我們可以輕鬆配置各種想要的三角形, 並且能實時查看css代碼. 開發完這個工具之後筆者再也不用擔心還需要手寫三角形代碼了.2.編輯器實現編輯器實現也是前端老生長談的話題了, 筆者在H5-Dooring項目中寫過一個非常複雜的編輯器, 但是這裡我們只要需要一個靜態且簡單的編輯器就夠了.
  • 精通react/vue組件設計之實現一個Tag(標籤)和Empty(空狀態)組件
    今天主要帶大家一起實現一個Tag組件和Empty(空狀態)組件,在介紹組件設計之前,先給大家介紹一個免費開源的圖標庫icomoon,可以在線導入SVG格式字體,並進行編輯,然後下載來使用,在組件設計中有具體的使用介紹.
  • ReactNative 的組件架構設計
    todo 一個問題:由於 react 是面向狀態編程,相當於 react 的組件只關注數據的最終狀態,數據是怎麼產生的並不關心,但是某些場景下,數據如何產生的是會影響到組件的一些行為的【比如一個新增行要求有動畫效果,查詢出的行就不需要等】,這在 RN 中很難描述。。。。。
  • Zarm 2.0 發布,基於 React 的組件庫
    確實,對於前端組件庫的大家庭來說,我們遲到了,但也請各位可以抽出幾分鐘看看一位初來乍到的新人的自我介紹:Zarm 是什麼Zarm 是眾安科技基於 React、React-Native 研發的一款適用於企業級的移動端 UI 組件庫。Zarm 的優勢多 組件多。
  • vue中簡單的axios二次封裝
    2)基於原生的XHR開發,XHR本身的架構不清晰,已經有了fetch的替代方案。Axios 是一個基於 promise 的 HTTP 庫,用於瀏覽器和node.js等http客戶端。符合最新的ES規範。
  • 「首席架構師推薦」關於React生態系統的一系列精選資源(2)
    react-table - React的輕量級,快速且可擴展的數據網格react-data-grid - 使用React構建的類似Excel的網格組件react-draggable - React draggable組件react-resizable-and-movable - React的可調整大小和可拖動的組件react-resizable - 一個簡單的React組件,可以使用句柄調整大小react-resizable-box
  • 基於Vue實現一個有點意思的拼拼樂小遊戲
    技術棧如下:vue-cli4 基於vue的腳手架Xuery 筆者基於原生js二次封裝的dom庫vue mvvm庫因為該應用屬於H5遊戲,為了清亮化筆者沒有採用第三方ui庫, 如果大家想採用基於vue的第三方移動端ui庫,筆者推薦如下:Mint 餓了麼推出的移動端ui庫NutUI 一套京東風格的移動端組件庫muse-ui 基於MaterialUI風格的移動端UI組件cube-ui
  • React 中高階函數與高階組件(上)
    >多個組件都需要某個相同的功能,使用高階組件減少重複實現react-redux 中的connect連接器就是一個高階組件export default connect(mapStateToProps, mapDispatchToProps
  • React組件邏輯復用的那些事兒
    而在此之前,或者如果你使用的是 React.createClass 的方式創建組件,那麼想要同樣的功能,就是使用 react-addons-pure-render-mixin,例如://下面代碼在新版React中可正常運行,因為現在已經無法使用 `React.createClass`,我就不使用 `React.createClass` 來寫了。
  • React Status 中文周刊 #8 - 100 行代碼實現 Facebook 的 Recoil React 庫
    — 支持可訪問性和定製化案例為了你更容易上手,我們封裝了這個 靈活又有趣的庫。VR/AR 是 UI 設計和實現領域的下一個爆點,最好試試這個工具。可以在這裡預覽 CodeSandbox。SurveyJS一個用 React 構建的實時交易系統 — 這個案例是關於 F/X 交易的實時交易系統
  • 前端: 如何利用Qrcode製作一個二維碼生成器?
    效果預覽 QR Code數據表示方法 : 深色模塊表示二進位"1",淺色模塊表示二進位"0"。Qrcode基本使用記憶如何包裝成自定義受控組件因為我們大多數項目目前都採用react或者vue開發了, 所以我們直接用對應的插件版本即可, 這裡筆者使用的是qrcode.react.
  • React系列教程
    1.sublime編輯器如何使用babel語法插件2.JSX中的函數使用3.React中的組件嵌套4.React中的父組件與子組件通信5.React中的子組件與父組件通信6.React父子組件數據交互小練習第八講:React選項卡原理及JSONP使用1.React選項卡的原理及製作
  • 精通react/vue組件設計之實現一個輕量級可擴展的模態框組件
    本文轉載自【微信公眾號:趣談前端,ID:beautifulFront】經微信公眾號授權轉載,如需轉載與原文作者聯繫前言本文是筆者寫組件設計的第九篇文章, 今天帶大家實現一個輕量級且可靈活配置組合的模態框(Modal)組件, 該組件在諸如Antd或者elementUI等第三方組件庫中都會出現
  • 【翻譯】基於 Create React App路由4.0的異步組件加載(Code...
    基於 Create React App路由4.0的異步組件加載 本文章是一個額外的篇章,它可以在你的React app中,幫助加快初始的加載組件時間。
  • 前端必備:React的生命周期和路由
    若變化了,this.setState將引起state變化,從而引起render,此時就沒必要再做第二次因重傳props引起的render了,不然重複做一樣的渲染了。2.組件本身調用setState,無論state有沒有變化。可通過shouldComponentUpdate方法優化。