Невозможно переместить div с помощью мышки в реакции - PullRequest
0 голосов
/ 01 ноября 2018

Я пытаюсь переместить div с помощью события mousemove.

Вот код для того же самого. https://codepen.io/anurag92/pen/VEoQOZ

class ImageMarker extends React.Component {

    constructor(props) {
        super(props);

        this.mouseDown = this.mouseDown.bind(this);
        this.mouseUp = this.mouseUp.bind(this);
        this.mouseMove = this.mouseMove.bind(this);
        this.paint = this.paint.bind(this);
    }

    mouseDown(e) {
        const position = {
            left: this.marker.offsetLeft,
            top: this.marker.offsetTop
        };

        this.hitOffset = {
            x: e.pageX - position.left,
            y: e.pageY - position.top,
            diameter: this.diameter(),
            markerRadius: 10
        };
        this.marker.addEventListener('mousemove', this.mouseMove);
        this.marker.addEventListener('mouseup', this.mouseUp);
        this.marker.addEventListener('mouseleave', this.mouseUp);
        e.preventDefault();
    }

    mouseMove(e) {
        this.position = {
            x: e.pageX - this.hitOffset.x,
            y: e.pageY - this.hitOffset.y
        };
        this.position.x = Math.round(this.position.x);
        this.position.y = Math.round(this.position.y);

        this.position.x = Math.min(700 - 1, Math.max(0, this.position.x));
        this.position.y = Math.min(700 - 1, Math.max(0, this.position.y));

        this.paint();
    }

    mouseUp(e) {
        this.marker.removeEventListener('mousemove', this.mouseMove);
        this.marker.removeEventListener('mouseup', this.mouseUp);
        this.marker.removeEventListener('mouseleave', this.mouseUp);
    }

    diameter() {
        return 1;
    }

    paint() {
        if (JSON.stringify(this.paintedPosition) !== JSON.stringify(this.position)) {
            this.paintedPosition = Object.assign({}, this.position);
        }

        if (this.position) {
            this.marker.style.left = `${100 * this.position.x / 700}%`;
            this.marker.style.top = `${100 * this.position.y / 700}%`;
        }
        return this;
    }

    render() {
        this.position = this.position || {
            x: 5,
            y: 5
        };
        this.offset = 0;
        return <div className='outer'
            ref = {ref => {
                this.canvasRef = ref;
            }}
        >
            <div className = 'marker'
                onMouseDown = {event => this.mouseDown(event)}
                ref = {ref => {
                    this.marker = ref;
                }} >
            </div>
        </div>;
    }

}

// export default ImageMarker;



ReactDOM.render(<ImageMarker />,
document.getElementById('root')
);

Когда я медленно двигаю свой курсор, он работает нормально, но при быстром движении срабатывает отпускание мыши, и в результате div не в состоянии угнаться за курсором.

Может кто-нибудь сказать, пожалуйста, потенциальное решение для этого.

1 Ответ

0 голосов
/ 01 ноября 2018

Вы можете решить эту проблему, прикрепив mouseMovemouseUp) ко всему document. Таким образом, они будут запущены независимо от того, выйдет ли мышь из элемента, который вы хотите перетащить. Просто не забудьте отсоединить событие во время componentWillUnmount, чтобы избежать утечек.

Более того, если вы хотите, чтобы ваш сайт работал на мобильном устройстве, вам нужно прикрепить события касания, указателя или перетаскивания. См. код кэндо-перетаскиваемой абстракции для справки. Мы используем его в наших реактивных компонентах. Привязать к элементу на ComponentDidMount и отсоединить на ComponentWillUnmount

...