React组件拖动不起作用,没有错误或控制台日志

时间:2016-10-30 03:52:03

标签: javascript reactjs

我尝试修改此SO帖子Recommended way of making React component/div draggable以使用es6类,但由于某些原因没有事件绑定被触发,但我没有收到任何错误。我的日志都没有打印任何内容。

// Dragging implementation https://stackoverflow.com/questions/20926551/recommended-way-of-making-react-component-div-draggable
export default class Clip extends Component {

  constructor(props) {
    super(props);
    this.state = {
      pos: this.props.initialPos,
      dragging: false,
      rel: null // position relative to the cursor
    };
  }

  /*  we could get away with not having this (and just having the listeners on
   our div), but then the experience would be possibly be janky. If there's
   anything w/ a higher z-index that gets in the way, then you're toast,
   etc.*/
  componentDidUpdate(props, state) {
    if (this.state.dragging && !state.dragging) {
      document.addEventListener('mousemove', this.onMouseMove);
      document.addEventListener('mouseup', this.onMouseUp);
    } else if (!this.state.dragging && state.dragging) {
      document.removeEventListener('mousemove', this.onMouseMove);
      document.removeEventListener('mouseup', this.onMouseUp);
    }
  }

  // calculate relative position to the mouse and set dragging=true
  onMouseDown(e) {
    console.log('onMouseDown', e);

    // only left mouse button
    if (e.button !== 0) return;
    var pos = $(this.getDOMNode()).offset();
    this.setState({
      dragging: true,
      rel: {
        x: e.pageX - pos.left,
        y: e.pageY - pos.top
      }
    });
    e.stopPropagation();
    e.preventDefault();
  }

  onMouseUp(e) {
    console.log('onMouseUp', e);

    this.setState({ dragging: false });
    e.stopPropagation();
    e.preventDefault();
  }

  onMouseMove(e) {
    if (!this.state.dragging) return;

    console.log('onMouseMove', e);

    this.setState({
      pos: {
        x: e.pageX - this.state.rel.x,
        y: e.pageY - this.state.rel.y
      }
    });
    e.stopPropagation();
    e.preventDefault();
  }

  render() {
    return (
      <div className="clip-component" style={ clipStyle(this.props) }>

      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

我在渲染的div中缺少onMouseDown={ this.onMouseDown }属性。