我想在单击或拖动它时将一个可拖动的框带到前面。
我事先不知道此类框的最大数量,因为我有一个按钮,当用户单击该按钮时会创建一个新的可拖动框。
无论有多少个盒子,按钮都应该始终位于顶部,因此它的 z-index 应该始终是最大的。
所以这些是我的问题:
我是 ReactJS 的新手。
这是我目前在 MyComponent.js 中的内容
import React, { useState } from 'react';
import Draggable from 'react-draggable';
function MyComponent() {
const [currZIndex, setZIndex] = useState(0);
const bringForward = () => {
setZIndex(currZIndex + 1);
}
return (
<Draggable onMouseDown={bringForward}>
<div className="mydiv" style={{zIndex: currZIndex}}></div>
</Draggable>
);
}
我当前实现的问题是每个组件只知道自己的 z-index,但不知道当前最高的 z-index 是多少。每当我点击任何 div 时,z-index 都会增加,因此这使得 z-index 不必要地变大。
如果 div1 的 z-index 为 6,div2 的 z-index 为 2,我必须单击 div2 5 次,使其 z-index 变为 7,才能将 div2 置于前面。
我还没有想出如何处理按钮的 z-index 的想法。
Fyr 这就是我在 App.js 中的内容
import React, { useState } from 'react';
import MyComponent from './MyComponent';
function App() {
const [componentList, setComponentList] = useState([]);
function addNewComponent() {
setComponentList(componentList.concat(<MyComponent key={componentList.length} />));
}
return (
<div>
<button onClick={addNewComponent}>New Component</button>
{componentList}
</div>
);
}
让我们一一解决这两个问题。首先是简单的:
1。如何让按钮无论有多少个盒子都保持在顶部,使其 z-index 始终最大?
实现此要求的一种方法是:
<button>
和 MyComponent
包裹在单独的 div
中。z-index
<button>
提供比div
MyComponent
更高的div
。position: relative
容器 (button
) 和 div
容器 (MyComponent
) 上使用 div
来建立单独的堆叠上下文。按照上述步骤,无论您创建多少个可拖动元素,
button
都将始终位于顶部。
return (
<div>
<div style={{ position: "relative", zIndex: 2 }}>
<button onClick={addNewComponent}>New Component</button>
</div>
<div style={{ position: "relative", zIndex: 1 }}>
{componentList.map((item) => (
<MyComponent
key={item.id}
zIndex={item.zIndex}
bringToFront={() => bringToFront(item.id)}
/>
))}
</div>
</div>
);
2。当用户单击/拖动可拖动框时,如何将其带到顶部(但在
button
后面)?
现在,要解决这个问题可以有多种方法。我使用的一种方法是使用视图中创建的可拖动组件的数量。让我详细说明将其分解为步骤。
在父组件中维护一个状态,该状态将跟踪可拖动组件的总数。
const [componentList, setComponentList] = useState([]);
使
<MyComponent />
(逻辑上每个可拖动的框)接受两个道具; zIndex
和 bringToFront
。
单击
button
在 componentList
(即 setState)内添加一个新条目,其中包含以下对象:
{
id: prevComponentList.length,
zIndex: 0,
}
现在,当单击拖动特定组件时(触发
mousedown
事件),并且使用该框的bringToFront
调用id
回调函数。现在,映射 componentList
并找到当前拖动/单击元素的 id
并将其 z-index
值增加到
prevComponentList
中可用元素的最大长度(如果
id
与该元素不匹配)
id
) 将当前 z-index 减少 1。
function bringToFront(id) {
setComponentList((prevComponentList) =>
prevComponentList.map((item) =>
item.id === id
? { ...item, zIndex: prevComponentList.length }
: { ...item, zIndex: item.zIndex - 1 },
),
);
}