React实现拖拽功能

我们都知道,js实现元素的拖拽分为下面三步:
1,拖拽元素绑定onmousedown,onmouseup事件
2,记录拖拽起始位置,鼠标按下时document绑定onmousemove事件,实时改变元素的布局style
3,鼠标放开时document移除onmousemove事件

这个要如何通过react实现呢,直接上代码:

<style>
    .dragable {
        height: 200px;
        width: 200px;
        background-color: red;
        position: fixed;
    }
</style>

<script type="text/babel">

    // 继承react的组件
    class Drag extends React.Component{
        constructor() {
            super()
            this.state = {
                needX: 0,
                needY: 0
            }
            this.disX = 0;
            this.disY = 0;
        }
        render() {
        	// 第一步:拖拽元素绑定onmousedown,onmouseup事件
            return <div className="dragable" style={{left:this.state.needX,top:this.state.needY}}
                onMouseDown = {this.fnDown.bind(this)}
                onMouseUp = {this.fnUp.bind(this)}
            >
                        
                    </div>
        }
        fnDown(e) {
        	// 第二步:记录拖拽起始位置,鼠标按下时document绑定onmousemove事件,实时改变元素的布局style
            this.disX = e.clientX - e.target.offsetLeft;
            this.disY = e.clientY - e.target.offsetTop;
            document.onmousemove = this.fnMove.bind(this)
        }
        fnMove(e) {
            this.setState({
                needX: e.clientX - this.disX,
                needY: e.clientY - this.disY
            })
        }
        fnUp() {
        	// 第三步:鼠标放开时document移除onmousemove事件
            document.onmousemove = null
        }
    }     
    ReactDOM.render(<Drag />, app)

</script>
发布了51 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/huzhenv5/article/details/103787204