我试图将类名分配给元素映射列表的前一个和下一个项目。当前项使用useState进行跟踪,并根据单击上一个/下一个按钮进行设置。
我的问题是,如何根据活动项选择上一个和下一个项目?
因为我映射到一个数组,我不能只是添加一个特定的数据属性,标记前一个,当前和下一个项目。(我认为)
无论如何,clickHandlers和stateSetters都按预期工作,我只需要弄清楚如何基于活动索引应用特定的上一个和下一个类,并在活动索引状态更改时更新它们。
这是我当前的代码:
在我的useEffect钩子中,我确实有逻辑来获取基于currentIndex的前一个和下一个项目,但我不知道如何选择这些元素,并为它们分配一个特定的类。
import { useEffect, useRef, useState } from "react"
import ArrowLeft from "../../../../assets/img/ArrowLeft"
import ArrowRight from "../../../../assets/img/ArrowRight"
import projectsData from "../../../../utils/projects.json"
export default function ProjectsNew() {
// const { currentSection } = useContext(CurrentSectionContext)
const [projects, setProjects] = useState([])
const projectsRef = useRef(null)
let [activeIndex, setActiveIndex] = useState(0)
useEffect(() => {
>! const prevIndex =
>! activeIndex - 1 >= 0 ? activeIndex - 1 : projects.length - 1
>!
>! const nextIndex =
>! activeIndex + 1 <= projects.length - 1 ? activeIndex + 1 : 0
setProjects(projectsData.projects)
}, [projects, activeIndex])
const handleNextClick = () => {
if (activeIndex + 1 <= projects.length - 1) {
setActiveIndex(activeIndex + 1)
} else {
setActiveIndex(0)
}
}
const handlePrevClick = () => {
if (activeIndex - 1 >= 0) {
setActiveIndex(activeIndex - 1)
} else {
setActiveIndex(projects.length - 1)
}
}
const setActiveClass = (index) => {
if (activeIndex === index) {
return " active"
} else {
return " inactive"
}
}
return (
<>
<div ref={projectsRef} className="projects_wrapper ">
{projects.map((project, index) => (
<div
data-index={index}
className={`project ${setActiveClass(index)}`}>
<img className="project_img" src={project.url} alt="." />
<div className="project_description">
<p className="project_description_text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident,
sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
<h2 className="project_title">{project.title}</h2>
<div className="project_btns">
<div className="btn_prev" onClick={() => handlePrevClick()}>
<ArrowLeft />
</div>
<div className="btn_next" onClick={() => handleNextClick()}>
<ArrowRight />
</div>
</div>
</div>
))}
</div>
</>
)
}
这基本上就是我想用一个简单的形式得到的:
<div classname="project inactive">
<div classname="project inactive prev">
<div classname="project active current">
<div classname="project inactive next">
<div classname="project inactive">
我想这样做,这样我就可以在增加/减少当前索引时应用特定的过渡。
您可以通过使用数组的索引来实现这一点,如
const isPrev = index + 1 === activeIndex
const isNext = index === activeIndex + 1
这段代码应该在你的map函数
中