我映射了Buttons数组并得到了三个按钮。我要实现的是能够确定单击了哪个按钮并添加活动的类
import React from "react";
import { useState } from "react";
import style from "./years.module.scss";
const Years = props => {
const [activeClass, setActiveClass] = useState(null);
const buttons = ["year one", "year two", "year three"];
return (
<div className={style.box}>
{buttons.map((button, index) => {
console.log(index,button)
return (
<button key={index} className={`${style.btn} ${style.active}`} >
{button}
</button>
);
})}
</div>
);
};
export default Years;
我使用css模块来设置按钮样式
答案 0 :(得分:2)
只需将处理程序与每个按钮连接-如果单击该按钮,则状态会更改并存储活动按钮的index
。如果它是活动的,请添加类。
const changeActiveButton = (i) => () => {
setActiveClass(i);
};
<button
onClick={changeActiveButton (index)}
className={`${style.btn} ${index === activeClass ? style.active : ''}`}
>