[英]React Hooks - Best way to remove an component temporarily from DOM without unmounting it
[英](Resolved )Best way to remove Draggable React component from flow without jumping?
我有使用notes.map()
呈現的 Note 組件,每個組件都有position: static
。 使用react-draggable
npm 模塊可以拖動筆記。
我想要實現的功能是在刪除筆記時,不影響用戶拖動的筆記的位置。 我試圖為已拖動的音符設置position: absolute
。 但是,這會導致音符“跳躍”一次(從流中移除時發生)。
-- 初始狀態: -- 在第一次拖動嘗試后,測試音符跳到其他音符的頂部: -- 第一次嘗試后可以正常拖動:
我已經包含了 Notes.jsx 組件的相關代碼:
function Note(props) {
const [dragDisabled, setDragDisabled] = useState(true);
const [beenDragged, setBeenDragged] = useState(props.beenDragged);
const [position, setPosition] = useState({ xPos: props.xPos, yPos: props.yPos });
// Drag Note Functions
function handleClick() {
setDragDisabled(prevValue => {
return !prevValue;
})
}
function firstDrag(event) {
if (!beenDragged) {
axios.post("api/note/beenDragged", {id: props.id})
.then(setBeenDragged(true));
}
}
function finishDrag(event, data) {
setPosition({ xPos: data.x, yPos: data.y });
}
useEffect(() => {
axios.post("/api/note/updateposition", {position, id: props.id });
}, [position]);
return <Draggable
disabled={dragDisabled}
onStart={firstDrag}
onStop={finishDrag}
defaultPosition={{ x: props.xPos, y: props.yPos }}
// position={location}
>
<div className='note' style={{position: beenDragged ? 'absolute' : 'static'}}>
<h1>{props.title}</h1>
<p>{props.content}</p>
<button onClick={handleClick}>
{dragDisabled ? <LockIcon /> : <LockOpenIcon />}
</button>
<EditPopup title={props.title} content={props.content} editNote={editNote} />
<DeletePopup deleteNote={deleteNote} />
</div>
</Draggable>
}
對於我的 CSS 樣式
.note {
background: #fff;
/* background-image: url("https://www.transparenttextures.com/patterns/notebook-dark.png"); */
background-image: url("https://www.transparenttextures.com/patterns/lined-paper-2.png");
border-radius: 7px;
box-shadow: 0 2px 5px rgb(120, 150, 179);
padding: 10px;
width: 240px;
margin: 16px;
float: left;
}
App.jsx 如何呈現注釋的相關代碼:
function App() {
const [notes, setNotes] = useState([]);
return (
<div id="bootstrap-override">
{notes.map((note) => {
return <Note
key={note._id}
id={note._id}
title={note.title}
content={note.content}
xPos={note.xPos}
yPos={note.yPos}
beenDragged={note.beenDragged}
deleteNote={deleteNote}
editNote={editNote}
/>
})}
</div>);
}
非常感謝任何幫助,謝謝!
我不是直接解決了這個問題,而是使用不同的方法來獲得我想要的結果。
總而言之,我對所有音符都使用了position: absolute
,並在邊界內的隨機 x,y 坐標處創建了它們。 這樣刪除的筆記不會影響現有筆記的位置。
希望這可以幫助任何有類似問題的人!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.