有多个按钮使用地图功能并显示。 想要更改我单击的按钮的背景颜色。而其他人则希望它保持原样。 再一次,当我点击另一个按钮时,只改变那个按钮的 BG 颜色。 有两个文件。一个组件 id 使用 map 函数定义按钮组件,另一个是按钮组件。 主要成分
state = {
categories: [],
selectedCategory: null,
value: 'test',
clicked1: false,
}
categorySelectedHandler = (id ,e) => {
this.setState({ selectedCategory: id });
}
const categoriesName = this.state.categories.map((category ,index) => {
// console.log("The current iteration is: " + index);
let visible_in_pricing_page = category.visible_in_pricing_page
if (visible_in_pricing_page) {
return <CategoryBtn
index = {index}
name={category.title}
key={category.id}
selectedId = {this.state.selectedCategory}
clicked={() => this.categorySelectedHandler(category.id)}
/>
}
});
CategoryBtn 组件 -
import React, { Component } from 'react';
import classes from './price-category-btn.css';
const CategoryBtn = props => {
return (
<div style={{display:"inline"}} >
<a>
<button
className= { classes.category_btn }
onClick={props.clicked}>{props.name}</button></a>
</div>
)
}
export default CategoryBtn;
你正在将
selectedId
属性传递给 CategoryBtn 组件,你可以使用它或者你可以传递一个布尔值
const categoriesName = this.state.categories.map((category, index) => {
// console.log("The current iteration is: " + index);
let visible_in_pricing_page = category.visible_in_pricing_page
if (visible_in_pricing_page) {
return <CategoryBtn
index = {
index
}
name = {
category.title
}
key = {
category.id
}
{/** indicate this is the selected button */}
selected = {this.state.selectedCategory === category.id}
clicked = {
() => this.categorySelectedHandler(category.id)
}
/>
}
});
在 categoryBtn 组件中返回带有动态类的按钮
<button
{/** use props.selected to dynamically set the class */}
className={`${classes.category_btn} ${props.selected}` ? classes.selectedCss : ''}
onClick={props.clicked}
>
{props.name}
</button>
在你的 CSS 模块中,你可以拥有背景颜色的类
.selectedCss
{ background-color: lightblue;}
对于那些不想处理 onClick 的人,只需覆盖按钮默认的 scss 调用即可。因此,例如,如果您想在活动/单击时更改所有主按钮,它看起来像这样:
index.css
.btn-primary:active {
--bs-btn-active-bg:#ff79c6;
--bs-btn-active-border-color: #ff79c6;
--bs-btn-active-color: #44475a;
}