简体   繁体   English

有没有办法为一组按钮添加一个活动的 class onClick?

[英]Is there a way to add an active class onClick for an array of buttons?

I map through the buttons array and get three buttons.我通过按键阵列 map 得到三个按键。 What i want to achieve is to be able to identify which button is clicked and add an active class我想要实现的是能够识别单击了哪个按钮并添加了一个活动的 class

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;

I use css modules to style the buttons我使用 css 模块来设置按钮样式

Just connect handler with each button - if clicked, the state is changed and stores the index of active button.只需将处理程序与每个按钮连接 - 如果单击,state 将更改并存储活动按钮的index If it's active - add class.如果它处于活动状态 - 添加 class。

const changeActiveButton = (i) => () => {
   setActiveClass(i);
};

<button 
   onClick={changeActiveButton (index)}
   className={`${style.btn} ${index === activeClass ? style.active : ''}`}
>
<button key={index} className={`${style.btn} ${style.active}`} onClick={()=>setActiveClass(button)} >
  {button}
</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM