我正在發出祝酒通知并嘗試實施職位選項。
我的問題是,當我將吐司放在底部,然后添加另一個時,新的出現在原來的位置,替換了第一個,第一個向下移動,最終離開了螢屏。
我想要實作的是讓第二個 toast 替換第一個,但第一個 toast 然后顯示 ABOVE,因此它們向上堆疊。
我在代碼沙箱上做了一個最小的例子
這是 reactjs 組件代碼,其中Toasts廣泛包含各個Toast組件的持有者:
import { useState } from "react";
import "./styles.css";
export default function App() {
const [toastState, setToastState] = useState([]);
const handleClick = (pos) => {
const ts = [...toastState];
ts.push({ id: ts.length, pos: pos });
setToastState(ts);
};
const Toast = ({ id, pos }) => {
return <div className={`toast ${pos}`}>{id}</div>;
};
const Toasts = () => {
const toasts = [...toastState];
const toastComps = toasts.reverse().map((t, i) => {
return <Toast key={i} id={t.id} pos={t.pos} />;
});
return <div>{toastComps}</div>;
};
return (
<div className="App">
<button
onClick={() => {
handleClick("bottom");
}}
>
Bottom
</button>
<Toasts className="toasts" />
</div>
);
}
這是CSS:
.toasts {
min-width: 100vw;
z-index: 9999;
position: fixed;
top: 0px;
left: 0px;
margin: 0px;
padding: 0px;
pointer-events: none;
}
.toast {
position: relative;
min-height: 50px;
min-width: 20rem;
margin: 5px;
padding: 5px;
border: 1px solid black;
border-radius: 5px;
}
.bottom {
bottom: -80vh;
}
關于如何實作這些 toast 組件自下而上堆疊的任何建議?
我嘗試使用 flexbox,例如將以下屬性添加到toasts容器類中:
display: flex;
flex-direction: column-reverse;
flex-wrap: wrap-reverse;
但是沒有效果。
我還嘗試了一個 js 解決方案,bottom根據 toast 的索引計算 的值:
const [bot, setBot] = useState(0);
useEffect(() => {
setBot(index ? 80 - (15*index) : 0);
}, [])
//then as an attribute to the `toast`div, after setting className for the position...
style={position.indexOf('bottom') > -1 && bot
? {bottom: `-${bot}vh`} : {}}
這更接近我所追求的,但是當敬酒超時或被解雇時,剩余的敬酒仍然在螢屏上 - 所以實際上整個串列都被拉到螢屏上,而不是按預期向上堆疊。
uj5u.com熱心網友回復:
這是一個簡化的解決方案。
import { useState } from "react";
import "./styles.css";
export default function App() {
const [toasts, setToasts] = useState([]);
const btnClicked = () => {
console.log("btnClicked");
setToasts([...toasts, { id: toasts.length }]);
};
return (
<div className="App">
<button onClick={btnClicked}>Bottom</button>
<div className="toasts">
{toasts
.map((toast) => <div className="toast">{toast.id}</div>)
.reverse()}
</div>
</div>
);
}
和 CSS :
.App {
font-family: sans-serif;
text-align: center;
}
.toasts {
position: fixed;
min-width: 100vw;
z-index: 9999;
position: fixed;
bottom: 0px;
left: 0px;
margin: 0px;
padding: 0px;
pointer-events: none;
overflow: hidden;
}
.toast {
position: relative;
min-height: 50px;
min-width: 10rem;
max-width: 10rem;
margin: 5px;
padding: 5px;
border: 1px solid black;
border-radius: 5px;
}
.bottom {
bottom: -80vh;
}
你可以在這里看到它的實際效果:CodeSandbox
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/461793.html
標籤:javascript css 反应
