Home Web Front-end H5 Tutorial How to implement react drag-and-drop sorting component using h5 (code attached)

How to implement react drag-and-drop sorting component using h5 (code attached)

Aug 13, 2018 pm 05:46 PM
html5 javascript react.js

The content of this article is about the method of using h5 to implement react drag and drop sorting components (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Drag-and-drop sorting component Github address: https://github.com/VicEcho/VD...

Because the react.js technology stack is used, the encapsulation prioritizes input and output. Render the page and control the order of dragging elements based on data drive.

Since I do not consider compatibility with older browsers such as IE8, the drag and drop effect uses HTML5 drag and drop (Drag and drop). Of course, if you require rich compatibility, it is also very simple to use mouse click-related events.

The effect achieved is as follows:

How to implement react drag-and-drop sorting component using h5 (code attached)

The first step is to understand the relevant attributes of H5 drag and drop. There are detailed information on MDN Instructions, the link is https://developer.mozilla.org...
One thing to note is that react.js will add "on" in front of all attribute event names, and the following will be written in camel case. For example, for native click events, onClick events should be used in react.js.

The drag and drop properties used by my component are as follows:

  1. draggable When set to true, the current control can be dragged

  2. onDragStart is an event triggered when the control starts to be dragged. It provides a dataTransfer.setData() method to store the necessary data in the object for easy calling in other methods.

  3. onDragOver A method that specifies that the current control can receive dragged components. Generally, bubbling is prevented in this method.

  4. onDragEnter is triggered when the mouse enters another acceptable area after dragging. This can be achieved by Move-in effect

  5. onDragLeave drag a to b, triggered when leaving b, can be used to monitor the timing of eliminating the move-in effect

  6. onDrop When the control Triggered when being "released" to a valid release target location, I process the data in this method and call the onChange method through it, exposing the value to the parent component

where draggable , onDragStart is the attribute that needs to be set by the "drag" side, onDragOver, onDragEnter, onDragLeave and onDrop are the attributes that need to be set by the "draged" side. However, for my drag-and-drop sorting component, each element is dragged and dropped.

The second step, since "she" is a component of react.js, according to custom, simply set the input attribute For value, at the same time, the onChange event is exposed to listen for changes in value and exposed to the parent component. At the same time, a property sortKey is exposed to tell the component which key to use as the sorting field.
Since it involves sorting and allows specifying the internal subcomponents of each element of the component, I define the input data format as an array object, in which the content can be reactNode:

 value: [
                {
                    content: 'p1',
                    code: '01',
                    sort: 0,
                },
                {
                    content: 'p2',
                    code: '02',
                    sort: 1
                },
                {
                    content: 'p3',
                    code: '03',
                    sort: 2
                },
                {
                    content: 'p5',
                    code: '05',
                    sort: 5
                },
                {
                    content: 'p4',
                    code: '04',
                    sort: 4
                }]
Copy after login

According to the value, I can generate For each node of the sorting component, the key code is as follows:

    // 生成拖拽组件
    createDraggleComponent(data, sortKey, style, uId) {
        return data.sort(this.compare(sortKey)).map((item) => {
            return (
                <p
                    className={styles.content}
                    key={item.code}
                    draggable={true}
                    onDragEnter={this.dragenter.bind(this)}
                    onDragLeave={this.dragleave.bind(this)}
                    onDragStart={this.domdrugstart.bind(this, item[sortKey], item.code, uId, item)}
                    onDrop={this.drop.bind(this, item[sortKey], data, sortKey, uId)}
                    onDragOver={this.allowDrop.bind(this)}
                    style={{ ...style }}>{item.content}</p>
            )
        })
    }
    render() {
        const { value, sortKey, style } = this.props;
        return (
            <Row>
                <p style={{ display: &#39;flex&#39;, flexDirection: &#39;row&#39; }}>
                    {this.createDraggleComponent(value, sortKey, style)}
                </p>
            </Row>
        )
    }
Copy after login

The specific implementation of the attribute method:

    // 拖动事件
    domdrugstart(sort, code, ee) {
        ee.dataTransfer.setData("code", code);
        ee.dataTransfer.setData("sort", sort);
    }
    // 拖动后鼠标进入另一个可接受区域
    dragenter(ee) {
        ee.target.style.border = &#39;2px dashed #008dff&#39;;
        ee.target.style.boxShadow = &#39;0 0 8px rgba(30, 144, 255, 0.8)&#39;;
    }
    // a拖到b,离开b的时候触发
    dragleave(ee) {
        ee.target.style.border = &#39;1px solid grey&#39;;
        ee.target.style.boxShadow = &#39;&#39;;
    }
    // 对象排序
    compare(key) {
        return (obj1, obj2) => {
            if (obj1[key] < obj2[key]) {
                return -1;
            } else if (obj1[key] > obj2[key]) {
                return 1;
            }
            return 0
        }
    }
    // 当一个元素或是选中的文字被拖拽释放到一个有效的释放目标位置时
    drop(dropedSort, data, sortKey, ee) {
        ee.preventDefault();
        const code = ee.dataTransfer.getData("code");
        const sort = ee.dataTransfer.getData("sort");
        if (sort < dropedSort) {
            data.map(item => {
                if (item.code === code) {
                    item[sortKey] = dropedSort;
                } else if (item[sortKey] > sort && item[sortKey] < dropedSort + 1) {
                    item[sortKey]--;
                }
                return item;
            });
        } else {
            data.map(item => {
                if (item.code === code) {
                    item[sortKey] = dropedSort;
                } else if (item[sortKey] > dropedSort - 1 && item[sortKey] < sort) {
                    item[sortKey]++;
                }
                return item;
            });
        }
        this.props.onChange(data)
    }
    allowDrop(ee) {
        ee.preventDefault();
    }
Copy after login

There is only one noteworthy point. When I controlled the order, I did not use it. target.before(document.getElementById({id})) to actually manipulate the node, but process the sorting of the data every time the onDrop time is triggered, and expose it to the parent component through the onChange event, output the data, and change the value The value triggers the virtual dom to re-render to control the order.

According to the company's requirements, on this basis, I also implemented the drag-and-drop copy function.

Related recommendations:

New attributes in HTML5: How to use the classList attribute

How does HTML5 solve the problem of margin-top collapse ( Code attached)

#What are the tags and common rules in HTML5? Introduction to html5 tags and rules


The above is the detailed content of How to implement react drag-and-drop sorting component using h5 (code attached). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles