Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize the simple drag-and-drop effect of Mobile and PC by typescript and react

Shulou Source: shulou.com Published: 2022-06-03 10:46:39 09月12日 Update

This article will explain in detail how typescript and react realize the simple drag-and-drop effect on mobile and PC. The editor thinks it is very practical, so I hope you can get something after reading this article.

The details are as follows

1. Mobile terminal

1.tsx code

Import {Component} from "react" Import'. / Tab.less'interface Props {} interface user {id: string, text: string} interface content {id: string, text: string} interface State {ButtonIndex: number, ButtonArray: user [], ContentArray: content []} class Tab extends Component {constructor (props: Props) {super (props) this.state = {ButtonIndex: 0 ButtonArray: [{id: '01percent, text:' button one'}, {id: '02percent, text:' button two'} {id: '03percent, text:' button three'}], ContentArray: [{id: 'c1marker, text:' content one'} {id: 'c2percent, text:' content two'}, {id: 'c3percent, text:' content three'}] }} FnTab (index: number): void {this.setState ({ButtonIndex: index})} render () {return ({this.state.ButtonArray.map ((item) Index) = > {item.text})} {this.state.ContentArray.map ((item, index) = > {item.text})}} export default Tab

2.css code

.drag {position: absolute; width: 100px; height: 100px; background-color: red;} II, PC side

1.tsx code

Import {Component CreateRef} from 'react'import'. / index.less'interface Props {} interface State {} class TextDrag extends Component {disX: number = 0 disY: number = 0 x: number = 0 y: number = 0 dragElement = createRef () constructor (props: Props) {super (props) this.state = {}} FnDown (ev: React.MouseEvent) {if (this.dragElement.current) {this.disX = ev.clientX-this.dragElement .current? .getboundingClientRect (). Left this.disX = ev.clientY-this.dragElement.current?.getBoundingClientRect (). Top} _ document.onmousemove = this.FnMove.bind (this) _ document.onmouseup = this.FnUp} FnMove (ev: MouseEvent) {this.x = ev.clientX-this.disX this.y = ev.clientY-this.disY if (this.dragElement.current) {this.dragElement.current.style.left = this .x + 'px' this.dragElement.current.style.top = this.y +' px'}} FnUp () {_ document.onmousemove = null _ document.onmouseup = null} render () {return ()}} export default TextDrag

2.css code

TextDrag {position: absolute; width: 100px; height: 100px; background-color: red;} this is the end of the article on "how typescript and react achieve simple drag and drop effects on mobile and PC". I hope the above content can be of some help to you so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Content code mobile buttons articles effects more good practical articles knowledge references help related Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Docker Redmi Microsoft OPPO Reno