React 實現(xiàn)側(cè)邊欄拖拽

項目背景:react+ts+less 常見使用按鈕來實現(xiàn)側(cè)邊菜單縮起/展開,現(xiàn)用代碼實現(xiàn)側(cè)邊欄拖拽寬度改變。

具體代碼實現(xiàn):

... react 類組件 部分關(guān)鍵代碼
 constructor(props: any) {
    super(props)
    this.state = {
      leftSideWidth: 300, // 側(cè)邊欄寬度
      tempWidth: 300,
      dragObject: {
        x: 0,
        y: 0
      }
    }
  }

  // 一般是在 mousedown 或者 dragstart 時觸發(fā)
  dragInit = (e: any) => {
    this.setState({ dragObject: { x: e.pageX, y: e.pageY } })
    window.addEventListener('mousemove', this.drag);
    window.addEventListener('mouseup', this.dragEnd);
    this.startDrag();
  }
  drag = (e: any) => {
    this.onMove(e.pageX - this.state.dragObject.x, e.pageY - this.state.dragObject.y);
  }
  dragEnd = () => {
    window.removeEventListener('mousemove', this.drag);
    window.removeEventListener('mouseup', this.dragEnd);
    this.setState({ dragObject: { x: 0, y: 0 } })
  }
  // 左側(cè)拖動
  onMove = (dx: any, dy: any) => {
    let width = this.state.tempWidth + dx
    let leftSideWidth = width < 200 ? 200 : width > 480 ? 480 : width // 最小200 最大480
    this.setState({ leftSideWidth: leftSideWidth })
  }
  startDrag = () => {
    this.setState({ tempWidth: this.state.leftSideWidth })
  }


render() {
    return (
      <div className='pages'>
        <div>
          <div className='line-left' style={{ width: this.state.leftSideWidth + 'px' }}>
            <h4>left</h4>
            <div className="drag-line" onMouseDown={this.dragInit}></div>
          </div>
        </div>
        <div>
          <h5>context</h5>
        </div>
      </div>
    );
  }


樣式關(guān)鍵部分:
cursor: col-resize;可出現(xiàn)雙向箭頭樣式

.line-left {
    height: 100vh;
    position: relative;
}
// 拖拽線
.drag-line {
  width: 4px;
  background: transparent;
  cursor: col-resize;
  z-index: 2;
  top: 0;
  bottom: 0;
  right: 0;
  position: absolute;
 &:hover {
    background-color: #bfbfbf;
  }
}

最終效果圖


側(cè)邊欄拖拽
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容