Перетащите элемент, не перемещайтесь к его цели, используя React DND - PullRequest
0 голосов
/ 06 августа 2020

Я уже искал похожую проблему, но с React Dnd не так много сообщений. Итак, я пришел сюда, чтобы узнать, может ли кто-нибудь мне помочь.

Я новичок в React и особенно в React Dnd, и я следовал этому руководству: https://react-dnd.github.io/react-dnd/docs/tutorial#creating -the-components .

Что я хочу сделать: Перетащите кнопку на простой доске, такой как доска в приведенном выше руководстве.

Моя проблема: Моя кнопка может перемещаться и находиться в состоянии "isDrag", если я уронил ее на квадрат (случай, если вы предпочитаете), его позиция изменится в коде (например, с [0, 0] на [1, 2] ), это хорошая вещь. НО, если посмотреть страницу в навигаторе, ничего не происходит, кнопка остается в том же квадрате!

Вот мой код:

Машина .jsx:

import React, { Component } from 'react';
import ImageMachine from './ImageMachine';
import { DndProvider } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import ButtonDnd from './ButtonDnd';
import './index.css';

export class Machine extends Component {
    static displayName = Machine.name;

    render() {
        return (
            <>
                <DndProvider backend={HTML5Backend}>
                    <div class="container">
                        <div class="row">
                            <div class="col">
                                <button type="button" class="btn btn-success">Add a new link</button>
                            </div>
                            <div class="col">
                                <h3 align="center">Test Machine</h3>
                            </div>
                            <div id="foobutton" class="col">
                                <ButtonDnd />
                            </div>
                        </div>
                    </div>
                    <br />
                    <ImageMachine />
                </DndProvider>
            </>
        );
    }
}

ImageMachine.jsx:

import React from 'react';
import Board from './Board';
import './index.css';

var position;
var posStr = "";

export function moveBtn(toX, toY) {
    position = [toX, toY];
    posStr = position.toString();
}

export default function ImageMachine() {
    if (position == null)
        position = [0, 0];

    posStr = position.toString();

    return (
        <>
            {posStr}
            <div className="bg">
                <Board position={position}/>
            </div>
            <br />
        </>
    )
}

Board.jsx:

import React from 'react'
import ButtonDnd from './ButtonDnd'
import DropSquare from './DropSquare';

function renderSquare(i, position) {
    const x = i % 8
    const y = Math.floor(i / 8)

    return (
        <div key={i} style={{ width: '12.5%', height: '12.5%' }}>
            <DropSquare x={x} y={y}>
                {renderBtn(x, y, position)}
            </DropSquare>
        </div>
    )
}

function renderBtn(x, y, [posX, posY]) {
    if (x === posX && y === posY) {
        return <ButtonDnd />
    }
}

export default function Board({ position }) {
    const squares = []
    for (let i = 0; i < 16; i++) {
        squares.push(renderSquare(i, position))
    }

    return (
        <div
            style={{
                width: '100%',
                height: '100%',
                display: 'flex',
                flexWrap: 'wrap'
            }}
        >
            {squares}
        </div>
    )
}

DropSquare.jsx:

import React from 'react';
import { ItemTypes } from './Constant'
import { useDrop } from 'react-dnd'
import { moveBtn } from './ImageMachine'
import Square from './Square';
import './index.css';

export default function DropSquare({ x, y, children }) {
    const [{ isOver }, drop] = useDrop({
        accept: ItemTypes.BUTTONDND,
        drop: () => moveBtn(x, y),
        collect: monitor => ({
            isOver: !!monitor.isOver()
        })
    })

    return (
        <div
            ref={drop}
            style={{
                position: 'relative',
                width: '100%',
                height: '100%'
            }}
        >
            <Square>{children}</Square>
            {isOver && (
                <div
                    style={{
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        height: '100%',
                        width: '100%',
                        zIndex: 1,
                        opacity: 0.5,
                        backgroundColor: 'yellow'
                    }}
                />
            )}
        </div>
    )
}

ButtonDnd.jsx:

import React from 'react';
import { ItemTypes } from './Constant'
import { useDrag } from 'react-dnd'

function ButtonDnd() {
    const [{ isDragging }, drag] = useDrag({
        item: { type: ItemTypes.BUTTONDND },
        collect: monitor => ({
            isDragging: !!monitor.isDragging(),
        }),
    })

    return (
        <>
            <div
                ref={drag}
                style={{
                    opacity: isDragging ? 0.5 : 1,
                    cursor: 'move',
                }}
            >
                <button type="button" class="btn btn-success">New button dragable</button>
            </div>
        </>
    );
}

export default ButtonDnd

Это мой первый пост на StackOverflow, не надо Не стесняйтесь сказать мне, если я что-то не так делаю, спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...