typescript+react实现移动端和PC端简单拖拽效果
程序员文章站
2022-06-16 22:25:29
本文实例为大家分享了typescript+react实现移动端和pc端简单拖拽效果的具体代码,供大家参考,具体内容如下一、移动端1.tsx代码import { component } from "re...
本文实例为大家分享了typescript+react实现移动端和pc端简单拖拽效果的具体代码,供大家参考,具体内容如下
一、移动端
1.tsx代码
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<props, state>{ constructor(props: props) { super(props) this.state = { buttonindex: 0, buttonarray: [ { id: '01', text: '按钮一' }, { id: '02', text: '按钮二' }, { id: '03', text: '按钮三' } ], contentarray: [ { id: 'c1', text: '内容一' }, { id: 'c2', text: '内容二' }, { id: 'c3', text: '内容三' } ], } } fntab(index: number):void { this.setstate({ buttonindex: index }) } render() { return ( <div classname='tab'> { this.state.buttonarray.map((item, index) => <button key={item.id} onclick={this.fntab.bind(this, index)} classname={this.state.buttonindex === index ? 'tab-button ac' : 'tab-button'}>{item.text}</button>) } { this.state.contentarray.map((item, index) => <div key={item.id} style={{display:this.state.buttonindex===index?'block':'none'}} classname='tab-content'>{item.text}</div>) } </div> ) } } export default tab
2.css代码
.drag { position: absolute; width: 100px; height: 100px; background-color: red; }
二、pc端
1.tsx代码
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<htmldivelement>() 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 ( <div classname="textdrag" ref={this.dragelement} onmousedown={this.fndown.bind(this)}> </div> ) } } export default textdrag
2.css代码
.textdrag{ position: absolute; width: 100px; height: 100px; background-color: red; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: 洛谷P3799 妖梦拼木棒