【发布时间】:2021-06-06 12:58:55
【问题描述】:
我有一个可水平滚动的 div 来呈现一些卡片。有一些按钮可以在单击时向左或向右(前后)变换 div。
我遇到的麻烦是试图弄清楚如何在到达最后一张卡片后禁用Next 按钮。禁用Back 按钮很简单,但我遇到了麻烦。
目前,它一直在无限向右滚动。
这是代码,
import * as React from "react";
function getRandomNumber(min, max) {
return Math.random() * (max - min) + min;
}
const cardWith = 200;
const cards = 10;
export default function Swipeable() {
const [currentTransform, setCurrentTransform] = React.useState(0);
const content = Array.from({ length: cards }, (_, index) => (
<div
style={{
minWidth: cardWith,
height: 300,
backgroundColor: `rgba(${getRandomNumber(0, 255)},${getRandomNumber(
0,
255
)}, ${getRandomNumber(0, 255)})`
}}
>
card {index}
</div>
));
return (
<div style={{ width: "100%", overflow: "hidden", position: "relative" }}>
<div
onClick={() => setCurrentTransform(currentTransform + 1)}
style={{
position: "absolute",
right: 10,
top: 100,
cursor: "pointer",
zIndex: 5,
display: "grid",
placeItems: "center",
width: 50,
height: 50,
transition: "0.25s",
backgroundColor: "cyan",
borderRadius: "0.25rem"
}}
>
Next
</div>
<div
onClick={() =>
currentTransform === 0
? undefined
: setCurrentTransform(currentTransform - 1)
}
style={{
position: "absolute",
left: 10,
top: 100,
display: "grid",
placeItems: "center",
cursor: "pointer",
zIndex: 5,
width: 50,
height: 50,
transition: "0.25s",
backgroundColor: "cyan",
borderRadius: "0.25rem"
}}
>
Back
</div>
<div
style={{
transition: "0.25s",
display: "flex",
transform: `translateX(-${currentTransform * cardWith}px)`
}}
>
{content}
</div>
</div>
);
}
【问题讨论】:
标签: javascript css reactjs