这篇文章将为大家详细讲解有关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; }
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; }
关于“typescript和react如何实现移动端和PC端简单拖拽效果”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。