在React中,拖动一个项目到另一个项目上时保持被拖动项目的大小。

huangapple go评论98阅读模式
英文:

Preserve the size of dragged item while dragging it over another item in react

问题

我正在创建一个应用程序,可以使用拖放功能对不同的句子进行排序,使用React。我的问题是当较小的项目被拖动到较大的项目上时,较小的项目会被拉伸。当较大尺寸的项目被拖动到较小尺寸的项目上时,较大的项目会收缩。

我需要在拖动时保持项目的大小不变。

有任何想法如何实现吗?

我的代码如下:

App.jsx

import React, { useState, useEffect } from 'react';
import { DndContext, closestCenter, useTransform } from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  verticalListSortingStrategy
} from '@dnd-kit/sortable';
import 'bootstrap/dist/css/bootstrap.min.css';
import { SortableItem } from './SortableItem.jsx';
import './App.css';

function App() {
  const [ranking, setRanking] = useState([
    "我不明白为什么人们不接受,无论如何,男孩都会是男孩,男人都会是男人",
    "她就是个话题制造机。",
    "不要像个胆小鬼。",
    "男人比女人开车技术更好。",
    "上帝是个男的。"
  ]);

  function handleDragEnd(event) {
    console.log('拖动');
    const { active, over } = event;
    console.log('激活:' + active.id);
    console.log('覆盖:' + over.id);

    if (active.id !== over.id) {
      setRanking((items) => {
        const activeIndex = items.indexOf(active.id);
        const overIndex = items.indexOf(over.id);
        console.log(arrayMove(items, activeIndex, overIndex));
        return arrayMove(items, activeIndex, overIndex);
      });
    }
  }

  return (
    <div>
      <DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
        <h3 style={{ color: 'black', fontWeight: 'bold' }} align="center">
          将以下句子按照最性别歧视到最不性别歧视的顺序排列
        </h3>
        <div className="frame">
          <SortableContext items={ranking} strategy={verticalListSortingStrategy}>
            {ranking.map((rank) => (
              <SortableItem key={rank} id={rank} className="sortable-item" />
            ))}
          </SortableContext>
          <div className="button" style={{ display: 'flex', justifyContent: 'center' }}>
            <button
              className="btn submit-button"
              align="center"
              onClick={(e) => {
                e.preventDefault();
                console.log(ranking);
              }}
            >
              提交
            </button>
          </div>
        </div>
      </DndContext>
    </div>
  );
}

export default App;

SortableItem.jsx

import React from "react";
import Card from 'react-bootstrap/Card';

import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";

export function SortableItem(props){
    //props.id
    const {
        attributes,
        listeners,
        setNodeRef,
        transform,
        transition
    } = useSortable({id: props.id});

    const style = {
        transform: CSS.Transform.toString(transform),
        transition,
        marginBottom: "1rem",
    };

    return (
        <div
            ref={setNodeRef}
            style={style}
            {...attributes}
            {...listeners}
            className="hover-card"
        >
            <Card body>{props.id}</Card>
        </div>
    );
}

我尝试使用了useTransform,useRef,为卡片提供了尺寸,还尝试使用了响应式的CSS,但效果不如预期。

PS,我对ReactJS非常新手。

谢谢

Sitashma

英文:

I am creating an app where different sentences can be ranked using drag and drop feature using react. My problem is whenever an item of smaller size is dragged over item of larger size, the smaller item streches. When an item with larger size is dragged over item with smaller size , the larger item shrinks.

在React中,拖动一个项目到另一个项目上时保持被拖动项目的大小。

在React中,拖动一个项目到另一个项目上时保持被拖动项目的大小。

I need to preserve the size of the dragged item when it is dragged.

Any idea how it can be done?

my code is as follow:

App.jsx

import React, { useState, useEffect } from &#39;react&#39;;
import { DndContext, closestCenter,useTransform } from &#39;@dnd-kit/core&#39;;
import {
arrayMove,
SortableContext,
verticalListSortingStrategy
} from &#39;@dnd-kit/sortable&#39;;
import &#39;bootstrap/dist/css/bootstrap.min.css&#39;;
import { SortableItem } from &#39;./SortableItem.jsx&#39;;
import &#39;./App.css&#39;;
function App() {
const [ranking, setRanking] = useState([
&quot;I dont understand why people dont accept that no matter what,Boys will be boys and men will be men&quot;,
&quot;She is such a drama queen.&quot;,
&quot;Don&#39;t be a sissy.&quot;,
&quot;Man is a better driver than women.&quot;,
&quot;God is a man.&quot;
]);
function handleDragEnd(event) {
console.log(&#39;Drag&#39;);
const { active, over } = event;
console.log(&#39;Active:&#39; + active.id);
console.log(&#39;Over :&#39; + over.id);
if (active.id !== over.id) {
setRanking((items) =&gt; {
const activeIndex = items.indexOf(active.id);
const overIndex = items.indexOf(over.id);
console.log(arrayMove(items, activeIndex, overIndex));
return arrayMove(items, activeIndex, overIndex);
});
}
}
return (
&lt;div&gt;
&lt;DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd} &gt;
&lt;h3 style={{ color: &#39;black&#39;, fontWeight: &#39;bold&#39; }} align=&quot;center&quot;&gt;
Rank the following sentences from most to least sexist.
&lt;/h3&gt;
&lt;div className=&quot;frame&quot;&gt;
&lt;SortableContext items={ranking} strategy={verticalListSortingStrategy}&gt;
{ranking.map((rank) =&gt; (
&lt;SortableItem key={rank} id={rank} className=&quot;sortable-item&quot; /&gt;
))}
&lt;/SortableContext&gt;
&lt;div className=&quot;button&quot; style={{ display: &#39;flex&#39;, justifyContent: &#39;center&#39; }}&gt;
&lt;button
className=&quot;btn submit-button&quot;
align=&quot;center&quot;
onClick={(e) =&gt; {
e.preventDefault();
console.log(ranking);
}}
&gt;
Submit
&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/DndContext&gt;
&lt;/div&gt;
);
}
export default App;

SortableItem.jsx

import React from &quot;react&quot;;
import Card from &#39;react-bootstrap/Card&#39;;
import { useSortable } from &quot;@dnd-kit/sortable&quot;;
import {CSS} from &quot;@dnd-kit/utilities&quot;;
export function SortableItem(props){
//props.id
const {
attributes,
listeners,
setNodeRef,
transform,
transition
} = useSortable({id: props.id});
const style = {
transform: CSS.Transform.toString(transform),
transition,
marginBottom: &quot;1rem&quot;,
};
return (
&lt;div
ref={setNodeRef}
style={style}
{...attributes}
{...listeners}
className=&quot;hover-card&quot;
&gt;
&lt;Card body&gt;{props.id}&lt;/Card&gt;
&lt;/div&gt;
);
}

I tried using useTransform, useref, giving dimension to the card, also tried using responsive css but it didnt work as expected.

PS, i am very new to reactjs

Thank you

Sitashma

答案1

得分: 1

您可以使用 useTransform 钩子自定义可排序项的变换和过渡属性。此钩子允许您根据元素的位置或状态应用自定义变换。例如,您可以像这样修改您的 SortableItem.jsx 文件:

import React from "react";
import Card from "react-bootstrap/Card";

import { useSortable, useTransform } from "@dnd-kit/sortable";

export function SortableItem(props) {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: props.id });

  const style = useTransform(
    transform,
    (transform) => {
      if (isDragging) {
        return {
          ...transform,
          width: "auto",
          height: "auto",
          margin: "1rem",
          boxShadow: "0 0 10px rgba(0,0,0,0.2)",
        };
      }
      return {
        ...transform,
        transition,
      };
    },
    [isDragging]
  );

  return (
    <div
      ref={setNodeRef}
      style={style}
      {...attributes}
      {...listeners}
      className="hover-card"
    >
      <Card body>{props.id}</Card>
    </div>
  );
}

这段代码使用 useTransform 钩子来根据拖动状态应用自定义样式变换,以及应用过渡效果。

英文:

You can customize the transform and transition properties of the sortable items using the useTransform hook. This hook allows you to apply custom transformations to draggable elements based on their position or state. For example, you can modify your SortableItem.jsx file like this:

import React from &quot;react&quot;;
import Card from &quot;react-bootstrap/Card&quot;;
import { useSortable, useTransform } from &quot;@dnd-kit/sortable&quot;;
export function SortableItem(props) {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: props.id });
const style = useTransform(
transform,
(transform) =&gt; {
if (isDragging) {
return {
...transform,
width: &quot;auto&quot;,
height: &quot;auto&quot;,
margin: &quot;1rem&quot;,
boxShadow: &quot;0 0 10px rgba(0,0,0,0.2)&quot;,
};
}
return {
...transform,
transition,
};
},
[isDragging]
);
return (
&lt;div
ref={setNodeRef}
style={style}
{...attributes}
{...listeners}
className=&quot;hover-card&quot;
&gt;
&lt;Card body&gt;{props.id}&lt;/Card&gt;
&lt;/div&gt;
);
}

huangapple
  • 本文由 发表于 2023年7月10日 18:09:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76652722.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定