Javascript。可拖动的div与React

时间:2018-11-30 08:03:42

标签: javascript html css reactjs

我正在尝试创建可拖动的div,但是我遇到了令人困惑的行为。该解决方案是从w3schools复制而来的,它对他们来说是正确的,但对我来说不是。 只需轻微移动鼠标,div始终会向左移动,即使鼠标向上或向下移动也是如此;只有向右移动较大的div,div才会跟随光标。

div.js

constructor(props){
    super(props)
    this.state = {
        x: this.props.x,
        y: this.props.y,
    }
    this.dragMouseDown = this.dragMouseDown.bind(this)
    this.elementDrag = this.elementDrag.bind(this)
    this.closeDragElement = this.closeDragElement.bind(this)
    this.reff = React.createRef()
}

componentDidMount(){
    this.pos1 = 0
    this.pos2 = 0
    this.pos3 = 0
    this.pos4 = 0
}

dragMouseDown(e) {
    e.preventDefault()
    this.pos3 = e.clientX
    this.pos4 = e.clientY
    document.onmouseup = this.closeDragElement
    document.onmousemove = this.elementDrag
}

elementDrag(e) {
    e.preventDefault()
    this.pos1 = this.pos3 - e.clientX
    this.pos2 = this.pos4 - e.clientY
    this.pos3 = e.clientX
    this.pos4 = e.clientY
    this.setState({
        y:(this.reff.current.offsetTop - this.pos2) + "px",
        x:(this.reff.current.offsetLeft - this.pos1) + "px",
    })
}

closeDragElement() {
    document.onmouseup = null
    document.onmousemove = null
}

render(){
    return (
        <div className="tech row align-items-center justify-content-center border rounded"
             style={{left: this.state.x, top: this.state.y}}
             onMouseDown={this.dragMouseDown}
             ref={this.reff}
        >
                <img className="technology-icon" src={image} alt="technology_logo"></img>
                <span className="ml-1">{this.props.name}</span>
        </div>
    )
}

具有此div和容器的CSS

.t_d{
    position: relative;
    width: 80%;
    height: 100%;
    overflow: hidden;
    overflow-x: auto;
    overflow-y: auto;
    border: 1px solid black;
}
 .tech{
    width: 150px;
    height: 50px;
    border-radius: 6px;
    position: absolute;
 }

为此使用html(行-div组件数组)

<div id="app"  style="height: 100%">
  <div className="fluid-container" style={{height: "100%"}}>
    <nav className="navbar navbar-dark bg-dark" id="nav">
        <a className="navbar-brand" href="#">Navbar</a>
    </nav>
    <div className="t_d">
            {rows}
    </div>
</div>
</div>

此外,我尝试执行类似下面的代码的方法,并且可以正常工作,但是我不喜欢将div移至光标这一事实

this.setState({
        y: e.clientY - this.height + this.td.scrollTop + "px",
        x: e.clientX + this.td.scrollLeft + "px"
    })

1 个答案:

答案 0 :(得分:0)

问题出在“技术”部门的“行”类中。删除它,一切开始按预期工作。哈哈哈。

<div className="tech border rounded"