基于Jsoneditor二次封装一个可实时预览的Json编辑器组件(React版)

开发 前端
做为一名前端开发人员,掌握vue/react/angular等框架已经是必不可少的技能了,我们都知道,vue或react等MVVM框架提倡组件化开发。

前言

做为一名前端开发人员,掌握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开发,这样适合团队开发组件库或者复杂项目组件的追溯和查错。

本文转载自微信公众号「趣谈前端」,可以通过以下二维码关注。转载本文请联系趣谈前端公众号。

责任编辑:姜华 来源: 趣谈前端
相关推荐

2023-04-10 08:30:30

json编辑器typescript

2021-05-05 11:34:09

前端开发技术热点

2022-01-12 09:01:52

前端技术编程

2022-10-17 08:03:47

封装vue组件

2021-12-05 21:05:49

前端JSON API

2020-12-15 08:58:07

Vue编辑器vue-cli

2010-02-23 15:52:14

Python编辑器

2024-03-20 09:31:00

图片懒加载性能优化React

2021-06-23 06:12:38

Subtitld编辑器开源

2021-01-03 16:57:43

heredoc文本编辑器Linux

2021-02-16 09:37:01

Filmulator开源图像编辑器

2016-09-30 10:16:39

sublimeswift

2022-06-02 09:09:27

前端React低代码编辑器

2014-03-24 09:19:43

Python编辑器

2017-03-29 12:30:58

LinuxLaTeXila编辑器

2014-09-05 09:45:46

2011-08-04 14:08:52

Reghance注册表编辑器

2021-12-23 10:59:30

开源技术 软件

2020-12-21 13:33:00

medit编辑器Linux

2011-08-04 18:49:50

注册表注册表编辑器
点赞
收藏

51CTO技术栈公众号