我有兩個按鈕。Prev和Next按鈕。在下面,我有一個horizontal div帶有多個專案的scroll bar.
這是 UI 的樣子:

滾動條運行良好。但我有上一個和下一個按鈕。當我點擊兩個按鈕時,它應該左右滾動。我試過了。但我不知道如何做出反應。
這是我嘗試過的代碼:
export default function App() {
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
return (
<div>
<div
style={{
display: "flex",
justifyContent: "flex-end",
gap: "50px",
marginBottom: "30px"
}}
>
<div style={{ cursor: "pointer" }}>Prev</div>
<div style={{ cursor: "pointer" }}>Next</div>
</div>
<div
style={{
display: "flex",
gap: "150px",
overflow: "scroll",
backgroundColor: "aqua"
}}
>
{data.map((item, index) => (
<div>item {item}</div>
))}
</div>
<div></div>
</div>
);
}
我不知道怎么做。請幫我解決一些問題。
uj5u.com熱心網友回復:
您可以使用 scrollLeft 屬性和 useRef。這是我的解決方案。
export default function App() {
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
const ref = React.useRef(null)
const handleScroll = (offset) => {
if (ref.current) {
ref.current.scrollLeft = offset;
}
}
return (
<div>
<div
style={{
display: "flex",
justifyContent: "flex-end",
gap: "50px",
marginBottom: "30px"
}}
>
<div onClick={() => handleScroll(-30)} style={{ cursor: "pointer" }}>Prev</div>
<div onClick={() => handleScroll(30)} style={{ cursor: "pointer" }}>Next</div>
</div>
<div
style={{
display: "flex",
gap: "150px",
overflow: "scroll",
backgroundColor: "aqua"
}}
ref={ref}
>
{data.map((item, index) => (
<div key={index}>item {item}</div>
))}
</div>
<div></div>
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/533026.html
上一篇:我需要一個使用javascript的井字游戲的重啟按鈕
下一篇:回應式導航漢堡選單不起作用
