在React JS中建立可拖曳的球體線條
P粉448130258
P粉448130258 2023-09-07 12:26:10
0
1
519

我有一個在線上可拖曳球的影片。我必須在react js 中實作該功能。球可以拖曳並越過線 鬆開球桿後,球桿不會回到原來的位置。

我嘗試了多種程式碼和方法,但沒有一個能按需要工作。我需要幫助來在 React 中創建這樣的功能,如果有人知道如何做,請幫助我。

const Ball = ({ color, onDragStart, onDragOver, onDrop }) => (
       <div
         className="ball"
         draggable
         onDragStart={onDragStart}
         onDragOver={onDragOver}
         onDrop={onDrop}
         style={{ backgroundColor: color }}
      />
     );


     import React, { useState } from 'react';
     import Ball from './Ball';

     const colors = ['red', 'blue', 'green', 'yellow'];

     const Line = () => {
     const [balls, setBalls] = useState(colors);

     const onDragStart = (e, index) => {
     e.dataTransfer.setData('index', index);
      };

      const onDragOver = (e) => {
      e.preventDefault();
      };

      const onDrop = (e, index) => {
    const droppedIndex = e.dataTransfer.getData('index');
    const newBalls = [...balls];
    newBalls.splice(droppedIndex, 1);
    newBalls.splice(index, 0, colors[droppedIndex]);
    setBalls(newBalls);
  };

  return (
    <div className="line">
      {balls.map((color, index) => (
        <Ball
          key={index}
          color={color}
          onDragStart={(e) => onDragStart(e, index)}
          onDragOver={onDragOver}
          onDrop={(e) => onDrop(e, index)}
        />
      ))}
    </div>
  );
};

此程式碼不起作用。

P粉448130258
P粉448130258

全部回覆(1)
P粉464113078
const Ball = ({ color, onDragStart, onDragOver, onDrop }) => (
       <div
         className="ball"
         draggable
         onDragStart={onDragStart}
         onDragOver={onDragOver}
         onDrop={onDrop}
         style={{ backgroundColor: color }}
      />
     );


     import React, { useState } from 'react';
     import Ball from './Ball';

     const colors = ['red', 'blue', 'green', 'yellow'];

     const Line = () => {
     const [balls, setBalls] = useState(colors);

     const onDragStart = (e, index) => {
     e.dataTransfer.setData('index', index);
      };

      const onDragOver = (e) => {
      e.preventDefault();
      };

      const onDrop = (e, index) => {
    const droppedIndex = e.dataTransfer.getData('index');
    const newBalls = [...balls];
    newBalls.splice(droppedIndex, 1);
    newBalls.splice(index, 0, colors[droppedIndex]);
    setBalls(newBalls);
  };

  return (
    <div className="line">
      {balls.map((color, index) => (
        <Ball
          key={index}
          color={color}
          onDragStart={(e) => onDragStart(e, index)}
          onDragOver={onDragOver}
          onDrop={(e) => onDrop(e, index)}
        />
      ))}
    </div>
  );
};
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板