[英]Is there a way to add an active class onClick for an array of buttons?
我通過按鍵陣列 map 得到三個按鍵。 我想要實現的是能夠識別單擊了哪個按鈕並添加了一個活動的 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;
我使用 css 模塊來設置按鈕樣式
只需將處理程序與每個按鈕連接 - 如果單擊,state 將更改並存儲活動按鈕的index
。 如果它處於活動狀態 - 添加 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.