我有五个div,当我单击时希望有一个活跃的班级。我的CSS中已经有一个活动的类,但是我不知道如何在代码中添加它
import React from 'react';
import './filter.scss';
const Filter = (props) => {
return (
<div className="filter">
<div className="filter__alle active">
<p>Alle</p> <span>2</span>
</div>
<div className="filter__eiendom ">
<p>Eiendom</p> <span>2</span>
</div>
<div className="filter__familie ">
<p>Familie</p> <span>2</span>
</div>
<div className="filter__kontrakt">
<p>Kontrakt</p> <span>2</span>
</div>
<div className="filter__husarbeid ">
<p>Husarbeid</p> <span>2</span>
</div>
</div>
);
}
export default Filter;
答案 0 :(得分:1)
我认为更好的方式将活动div索引保存为状态:
import * as React from "react";
import "./styles.css";
const data = [
{ name: "Alle", text: 2 },
{ name: "Eiendom", text: 2 },
{ name: "Familie", text: 2 },
{ name: "Kontrakt", text: 2 },
{ name: "Husarbeid", text: 2 }
];
const Filter = props => {
const [activIndex, setActiveIndex] = React.useState(null);
const handleClick = index => {
console.log(index);
setActiveIndex(index);
};
return (
<div className="filter">
{data.map((item, index) => (
<div
key={index}
className={
activIndex === index ? "filter__item active" : "filter__item"
}
onClick={() => handleClick(index)}
>
<p>{item.name}</p> <span>{item.text}</span>
</div>
))}
</div>
);
};
export default Filter;
答案 1 :(得分:0)
添加活动班级
import styles from './filter.scss';
<div className={`${styles.active} filter__alle active`}>
<p>Alle</p> <span>2</span>
</div>
答案 2 :(得分:0)
我认为OP希望通过一个对象映射数据,并为每个对象设置不同的点击处理程序。在这种情况下,您只需切换当前目标元素的class属性即可。指的是我的代码,
const Filter = (props) => {
const list = ["Alle", "Eiendom", "Familie", "Kontrakt", "Husarbeid"]
const handleClick = e => {
e.target.classList.toggle("active");
}
return (
<div className="filter">
{list.map(name => (
<div className="filter__alle" key={name} onClick={handleClick}>
<p>{name}</p> <span>2</span>
</div>
))}
</div>
);
}