Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to encapsulate a json Editor with Real-time Preview in web Development

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Today, I will talk to you about how to encapsulate a json editor that can be previewed in real time in web development. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

The trees give welcome shade

As a front-end developer, it is necessary to master frameworks such as vue/react/angular. As we all know, MVVM frameworks such as vue or react advocate component-based development, which on the one hand can improve component reusability and expansibility, on the other hand, it also brings flexibility and maintainability of project development, and facilitates multi-person development cooperation. The next article will show how to use react to develop a custom json editor component. We use the third-party library jsoneditor, official address: jsoneditor through the implementation of an json online editor to learn how to package their own components step by step (not limited to react,vue, the principle is similar).

Design ideas

Before introducing the idea of component design, it is necessary to introduce the famous SOLID principle.

SOLID (single function, open-close principle, Richter substitution, interface isolation and dependency inversion) are the five basic principles of object-oriented programming and object-oriented design put forward by Robert C. Martin. Using these principles, programmers can develop a maintainable and extensible system more easily and efficiently. SOLID is typically used in test-driven development and is an important part of the basic principles of agile development and adaptive software development.

S single function principle: specifies that each class should have a single function, and that function should be fully encapsulated by this class. All its services should be closely consistent with this function.

O opening and closing principle: states that "objects (classes, modules, functions, etc.) in the software should be open to extensions, but closed to modifications." this means that an entity is allowed to change its behavior without changing its source code. Code that follows this principle does not need to be changed when extended.

L-Richter substitution principle: a derived class (subclass) object can replace its base class (superclass) object in a program, which is a special definition of a subtype.

I interface isolation principle: indicates that an application or object should not depend on methods it does not use. Interface isolation principle (ISP) splits very large and bloated interfaces into smaller and more specific interfaces so that applications or objects only need to know the methods they are interested in. This narrowed interface is also known as a role interface. The purpose of the Interface isolation principle (ISP) is to decouple the system so that it is easy to reconfigure, change, and redeploy. The principle of interface isolation is one of the five principles of object-oriented design (OOD) in SOLID (object-oriented design), similar to the high cohesion in GRASP (object-oriented design).

D dependency inversion principle: refers to a specific form of decoupling, so that the high-level module does not rely on the implementation details of the low-level module, and the dependency relationship is reversed (reversed). Thus, the low-level module depends on the requirement abstraction of the high-level module.

Mastering these five principles will help us to develop better components, please remember silently. Next let's take a look at the design idea of the json editor.

As shown above, like any input box, with reference to the design of the antd component and compatibility with antd's form form, we provide the onChange method. (details will be described in more detail below)

First of all, using the basic style of jsoneditor rendering and API, we can implement a basic usable json editor, then bind data bidirectionally through exposed json and onChange attributes, monitor exceptions or input errors through onError, and modify the default theme color through themeBgColor. Through these interfaces, we can fully grasp the operation of a component.

Text

Then we will officially begin our text. Because the components of this paper are based on react, but when used on vue,angular, the basic pattern is also applicable. The key is to master the life cycle of different frameworks.

Before learning to implement json editor components, it is necessary to understand the use of jsoneditor as a third-party component and api.

The use of jsoneditor

Installation

Let's first execute npm install to install our components

Npm install jsoneditor

Secondly, introduce the style file manually

This way, we can use its api:

/ / create editor var container = document.getElementById ("jsoneditor"); var editor = new JSONEditor (container) / / set json data 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);} / / get json data function getJSON () {var json = editor.get (); alert (JSON.stringify (json, null, 2));}

So you may see the following interface:

In order to achieve real-time preview and editing, this is not enough, we need additional processing. We need to use jsoneditor's other api and techniques.

Combined with react for secondary packaging

Based on what has been discussed above, we can easily encapsulate the editor as a react component, and we only need to initialize the instance during the componentDidMount lifecycle. The react code might look like this:

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 this.container = elem} / >}} export default JsonEditor

As for the options in options, we can refer to jsoneditor's API document, which is very detailed, through the above code, we can implement a basic react version of the json editor component. Next, we will follow the design idea to implement the real-time preview json editor component step by step.

1. Implement preview and edit views

In fact, this is easy to achieve, we only need to instantiate two editor instances, one for preview and one for editing.

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 (this.container = Elem} / > this.viewContainer = elem} / >) }} export default JsonEditor

In this way, we can implement a preliminary editor that can be previewed in real time. The effect may look like this:

It is close to the mature version, but there are still a lot of details to deal with.

two。 Expose properties and methods to support import React requirements in different scenarios {PureComponent} from 'react' import JSONEditor from' jsoneditor' import 'jsoneditor/dist/jsoneditor.css' class JsonEditor extends PureComponent {/ / listen for changes in input values onChange = () = > {let value = this.jsoneditor.get () this.props.onChange & & this.props.onChange (value) this.viewJsoneditor.set (value)} / / json data of the external exposure acquisition editor getJson = () = > { This.props.getJson & & this.props.getJson (this.jsoneditor.get ())} / / submit error message 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 () / / sets the theme color this.container.querySelector ('.jsoneditor'). 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 = `style$ {this.props.themeBgColor} `} componentDidUpdate () {if (this.jsoneditor) {this.jsoneditor.update (this.props.json) this.viewJsoneditor.update (this.props.json)}} render () {return (this.container = elem}) / > this.viewContainer = elem} / >) }} export default JsonEditor

Through the above process, we have completed more than half of the work, the remaining details and optimization work, such as how to uninstall the instance when the component is unloaded, type checking of the component, etc., we continue to complete the above problems.

3. Use PropTypes for type detection and clear instances when components are uninstalled

Type checking is supported internally by react. When you install react, you will automatically install PropTypes for us. For more information, please refer to the propTypes document of the official website. Secondly, we will clear the editor instance in the componentWillUnmount life cycle of react to free memory. The complete code is as follows:

Import React {PureComponent} from 'react' import JSONEditor from' jsoneditor' import PropTypes from 'prop-types' import' jsoneditor/dist/jsoneditor.css' / * JsonEditor * @ param {object} json json data used for binding * @ param {func} callback when onChange changes * @ param {func} getJson provides the outside with a way to go back to json * @ param {func} onError provides the external json malformed callback * @ param {string } themeBgColor modifies theme color for external exposure * / 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 () / / sets the theme color this.container.querySelector ('.jsoneditor'). 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 = `style$ {this.props.themeBgColor} `} componentWillUnmount () {if (this.jsoneditor) {this.jsoneditor.destroy () this.viewJsoneditor.destroy ()}} componentDidUpdate () {if (this.jsoneditor) {this.jsoneditor.update (this.props.json) This.viewJsoneditor.update (this.props.json)}} render () {return (this.container = elem} / > this.viewContainer = elem} / >) }} JsonEditor.propTypes = {json: PropTypes.object, onChange: PropTypes.func, getJson: PropTypes.func, onError: PropTypes.func, themeBgColor: PropTypes.string} export default JsonEditor

Because the components strictly follow the open-close principle, we can provide more customized functions in our json editor to meet the requirements of different projects. For the discussion of the robustness of component development, in addition to using propTypes, it can also be developed based on typescript, which is suitable for team development component library or complex project component traceability and error checking. The final effect is as follows:

The author has published the implemented components to npm. If you are interested, you can use npm directly after installation, as follows:

Npm I @ alex_xu/xui / / Import xui import {Button, Skeleton, Empty, Progress, Tag, Switch, Drawer, Badge, Alert} from'@ alex_xu/xui'

The component library supports on-demand import. We only need to configure babel-plugin-import in the project, as shown below:

/ / .babelrc "plugins": [["import", {"libraryName": "@ alex_xu/xui", "style": true}]]

The screenshot of the npm library is as follows:

After reading the above, do you have any further understanding of how to re-package a json editor that can be previewed in real time in web development? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report