1. 程式人生 > 其它 >基於jsoneditor二次封裝一個可實時預覽的json編輯器元件(react版)

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

前言

做為一名前端開發人員,掌握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開發,這樣適合團隊開發元件庫或者複雜專案元件的追溯和查錯.

LowCode視覺化低程式碼社群介紹

LowCode低程式碼社群(http://lowcode.dooring.cn)是由在一線網際網路公司深耕技術多年的技術專家創辦,意在為企業技術人員提供低程式碼視覺化相關的技術交流和分享,並且鼓勵國內擁有相關業務的企業積極推薦自身產品,為國內B端技術領域積累知識資產。同時我們還歡迎開源大牛們分享自己的開源專案和技術視訊