我有一個在線上可拖曳球的影片。我必須在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粉4641130782023-09-08 11:17:46
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> ); };