【发布时间】:2021-10-16 10:50:17
【问题描述】:
我刚开始学习 CSS 模块的使用。
我要做的是创建一个滑块,我如何实现它的功能是通过使用“activeSlide”、“nextSlide”和“lastSlide”动态更改我的 className。但是,我对 CSS 模块有一个问题,我不知道在我的 className 中放置什么来进行动态定位并同时应用与每个位置对应的 CSS 属性。如何使用 CSS 模块在一个 className 中实现这两种功能。
这是我的 index.jsx 文件,
import React, { useState, useEffect } from 'react';
import {FiChevronRight, FiChevronLeft} from 'react-icons/fi';
import reviewdata from './reviewdata';
import styles from './index.module.css';
export default function Review(){
const randomizer =()=>{
let number = Math.floor(Math.random()* (people.length))
return number;
}
const [people, setPeople]= useState(reviewdata);
const [index, setIndex] = useState(randomizer());
useEffect(()=>{
const lastIndex = people.length - 1;
if (index < 0){
setIndex(lastIndex);
}
if (index > lastIndex){
setIndex(0);
}
},[index,people]);
useEffect(()=> {
let slider = setInterval(()=>{
setIndex(index + 1);
},4000)
return ()=> clearInterval(slider)
},[index])
return (
<section className={styles.main}>
<div className={styles.title}>
<h2>Reviews</h2>
</div>
<div className={styles.review_main}>
{people.map((person, personIndex)=>{
const {id, username, userphoto, description, reviewphoto, star} = person;
let position = 'nextSlide';
if(personIndex === index){
position = 'activeSlide';
}
if(personIndex === index - 1 || (index === 0 && personIndex === people.length - 1)){
position = 'lastSlide';
}
return (
// still need to fix styles with dynamic position
<article className={`${styles.article} ${styles.position}`} key={id}>
<img src={userphoto} alt={username} className={styles.person_img}/>
<h4>{username}</h4>
<p className={styles.title}>{star}</p>
<p className={styles.text_review}>{`"${description}"`}</p>
<img className={styles.review_img} src={reviewphoto} alt={username} />
</article>
)
})}
<button className={styles.prev} onClick={()=> setIndex(index - 1)}>
<FiChevronLeft/>
</button>
<button className={styles.next} onClick={()=> setIndex(index + 1)}>
<FiChevronRight/>
</button>
</div>
</section>
)
}
这是我的 index.module.css,这里我只显示文章标签部分。
article {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: var(--transition);
}
article.activeSlide {
opacity: 1;
transform: translateX(0);
}
article.lastSlide {
transform: translateX(-100%);
}
article.nextSlide {
transform: translateX(100%);
}
【问题讨论】:
标签: javascript html css reactjs css-modules