基于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.themeBgColorthis.container.querySelector('.jsoneditor').style.border = `thin solid ${this.props.themeBgColor}`this.viewContainer.querySelector('.jsoneditor-menu').style.backgroundColor = this.props.themeBgColorthis.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.themeBgColorthis.container.querySelector('.jsoneditor').style.border = `thin solid ${this.props.themeBgColor}`this.viewContainer.querySelector('.jsoneditor-menu').style.backgroundColor = this.props.themeBgColorthis.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开发,这样适合团队开发组件库或者复杂项目组件的追溯和查错.
最后
如果想了解更多H5游戏, webpack,node,gulp,css3,javascript,nodeJS,canvas数据可视化等前端知识和实战,欢迎在公众号《趣谈前端》加入我们一起学习讨论,共同探索前端的边界。
知识汇总系列推荐
web性能优化的15条实用技巧
前端必不可少的Git使用技巧
《javascript高级程序设计》核心知识总结
前端开发中不可忽视的知识点汇总(一)
css3实战汇总(附源码)
让你瞬间提高工作效率的常用js函数汇总(持续更新)
欢迎关注下方公众号,获取更多前端知识精粹和加入学习社群:
回复 Webpack,可获得 用webpack4.0撸单页/多页脚手架思维导图
回复 lodash,将获得 本人亲自翻译的lodash API中文思维导图
回复 学习路径,将获取 笔者多年从业经验的前端学习路径的思维导图
趣谈前端
Vue、React、小程序、Node
前端 算法|性能|架构|安全
基于jsoneditor二次封装一个可实时预览的json编辑器组件(react版)相关推荐
- antd picker 使用 如何_如何基于jsoneditor二次封装一个可实时预览的json编辑器组件?(react版)...
前言 做为一名前端开发人员,掌握vue/react/angular等框架已经是必不可少的技能了,我们都知道,vue或react等MVVM框架提倡组件化开发,这样一方面可以提高组件复用性和可扩展性,另一 ...
- 富文本编辑器 输出在线html_一个在线实时预览代码编辑器的实现
在线代码编辑器--Html/Markdown支持 作为开发者,经常会使用各式编辑器,一个体验良好的编辑器会给使用者舒适的coding体验. 但当我们不是使用自己熟悉的电脑,在任意的环境下,我们就需要有 ...
- html 实时预览在线,用HTML+CSS做一个实时预览的markdown编辑器
markdown编辑器 *{margin:0;padding:0;outline:none;border-radius:0; } html,body{width:100%;height:100%;fo ...
- window7 海康硬盘录像机+ffmpeg+nginx+ckplayer实现网页实时预览监控视频(无敌详细版)
公司要求,将大华,海康威视的硬盘录像机的监控视频在网页端统一显示,网上的文章大部分都是在服务器上的操作,本人小白一个所以踩了几个坑(之前尝试过用编写ocx,不过比较难,而且兼用性也不好),以下是根据博 ...
- 用户收货地址h5页面_如何实现H5可视化编辑器的实时预览和真机扫码预览功能...
前言所见即所得的设计理念在WEB IDE领域里一直是备受瞩目的功能亮点, 也能极大的提高 web coder的编程体验和编程效率. 笔者接下来就将对H5可视化编辑器的实时预览和真机扫码预览功能做一次方 ...
- 用户收货地址h5页面_如何实现H5可视化编辑器的实时预览和真机扫码预览功能?...
前言 所见即所得的设计理念在WEB IDE领域里一直是备受瞩目的功能亮点, 也能极大的提高 web coder的编程体验和编程效率. 笔者接下来就将对H5可视化编辑器的实时预览和真机扫码预览功能做一次 ...
- 如何实现H5可视化编辑器的实时预览和真机扫码预览功能
往期精彩 基于NodeJS从零构建线上自动化打包工作流(H5-Dooring特别版) 在线IDE开发入门之从零实现一个在线代码编辑器 基于React+Koa实现一个h5页面可视化编辑器-Dooring ...
- h5案例欣赏及分析_如何实现H5可视化编辑器的实时预览和真机扫码预览功能
往期精彩 基于NodeJS从零构建线上自动化打包工作流(H5-Dooring特别版) 在线IDE开发入门之从零实现一个在线代码编辑器 基于React+Koa实现一个h5页面可视化编辑器-Dooring ...
- 基于Dapper二次封装了一个易用的ORM工具类:SqlDapperUtil
基于Dapper二次封装了一个易用的ORM工具类:SqlDapperUtil,把日常能用到的各种CRUD都进行了简化封装,让普通程序员只需关注业务即可,因为非常简单,故直接贴源代码,大家若需使用可以直 ...
- 基于Python的双USB摄像头实时预览保存软件
基于PyQt5,opencv,实现双usb外接摄像头拍摄存储 双摄像头支持单独开启关闭,实时预览视频,单独/同时保存预览视频图片 多线程模式,支持掉线重连(有点bug,因无法绑定设备id,画面会出现错 ...
最新文章
- 2019成考计算机几时出成绩,2019年成人高考成绩什么时候出来?如何查询
- 使用页面元素属性做状态判断的隐患
- 深入XP之认识的引导文件NTLDR
- The directory '*' or its parent directory is not owned by the current user
- 群同态基本定理证明_群论(7): 群代数, 群表示基础
- 搜索研发工程师需要掌握的一些技能
- 窗口变化相关消息 OnSize、OnSizing和OnGetMinMaxInfo
- Cookie和Session有什么区别?
- Layer 提示框tips使用(批量提示)
- 3ds Max 2012 简体中文版 带注册机32位64位
- java .jar怎么打开_详解jar文件怎么打开
- Texlive安装宏包
- HCIP RS IERS题之OSPF(二)
- 简单线性相关案例-求相关系数
- C语言小写转大写,小写字母转换成大写字母!
- Word文档进行XXE攻击
- 解决真机识别为虚拟机,Sorry, this application cannot be run under a Virtual Machine
- 【原创】快速上手使用思维导图
- u盘正常接入后计算机无法看到,U盘连接到电脑之后,电脑无反应怎么办?
- 使用FileZilla连接时超时,无法连接到服务器