[英]How to change the button colour when it is clicked
I have this set of buttons from A to Z when I click on the particular alphabet the brands related to that letter will pop up.我有这组从 A 到 Z 的按钮,当我单击特定字母时,与该字母相关的品牌会弹出。 I have tried the below code but it is applying for all the buttons when I click only one button.
我已经尝试了下面的代码,但是当我只单击一个按钮时它正在申请所有按钮。 How do I solve it
我该如何解决
let brandList = 'ABCEDEFGHIJKLMNOPQRSTUVWXYZ'.split("");
constructor(props) {
super(props)
this.state = {
bgColor: ""
}
}
getBrandSortData(){
return(
<div className="BrandPageList_AlphabetContainer">
<button value="all" className="BrandPageList_AllButton" onClick={this.handleClick}>All</button>
{brandList.map((item,index) =>
{
let disbaled = !this.isBrandCharacterAvailable(item)
return(
<button
disabled= {disbaled}
value={item}
key={index}
block="BrandPageList_AlphabetButtons"
mods = {{enabled : !disbaled}}
onClick={this.handleClick}
style={{backgroundColor: this.state.bgColor}}
>
{item}
</button>
)}
)}
</div>
)
}
handleClick = event =>{
const brandValues = event.target.value
if(brandValues === "all"){
console.log()
return this.setAllBrands()
}
else{
let brandSortDataByCharacter = this.state.brandSortData[brandValues]
this.setState({
allBrands:
{
[brandValues]: brandSortDataByCharacter
},
bgColor: "red"
})
}
}
Instead of using the event
object to determine what letter you clicked on, you can pass the letter to the click handler when you render it.除了使用
event
object 来确定您单击了哪个字母,您可以在呈现它时将字母传递给单击处理程序。
Here's an example of how you can achieve this.这是一个如何实现这一目标的示例。 I'm using a functional component with hooks, since this is the recommended way, but you can do the same in a class component:
我正在使用带有钩子的功能组件,因为这是推荐的方式,但您可以在 class 组件中执行相同的操作:
const Alphabet = () => {
const [active, setActive] = useState();
return (
<div className='alphabet'>
{'ABCEDEFGHIJKLMNOPQRSTUVWXYZ'.split('').map(char => (
<div
className={`letter ${char === active ? 'active' : ''}`}
onClick={() => setActive(char)}>{char}</div>
))}
</div>
);
};
And here's a live example这是一个活生生的例子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.