1.效果
class写法
import React, { Component } from 'react';
import "./1.css"
class B extends Component {
province = ["1月","2月","3月","4月","5月","6月",]
state={
selectmonth:[]
}
btnclick=(item)=>{
const {selectmonth=[]}=this.state
if(!selectmonth.includes(item)){
this.setState({selectmonth:[...selectmonth,item]},()=>console.log(this.state.selectmonth))
}
else{
const index =selectmonth.findIndex(i =>i==item );
selectmonth.splice(index,1)
this.setState({selectmonth:[...selectmonth]},()=>console.log(this.state.selectmonth))
}
}
render() {
const {selectmonth=[]}=this.state
return (
<div className="box">
{this.province?
this.province.map((item)=>{
return(
<span
key={item}
className={`item_span ${selectmonth.includes(item)?'item_span_choose': ''}` }
onClick={()=>{
this.btnclick(item)
}}>
{item}
</span>
)
}):null}
</div>
);
}
}
export default B;
hooks写法
import "./1.css";
import React, { Component, useEffect, useState } from "react";
const A=()=> {
const [selectmonth, setSelectmonth] = useState([]);
const province = ["1月", "2月", "3月", "4月", "5月", "6月"];
const btnclick = item => {
// 单选
// if (!selectmonth?.includes(item)) {
// setSelectmonth(item);
// }
// console.log(selectmonth)
// 全选
if (!selectmonth?.includes(item)) {
setSelectmonth([...selectmonth, item]);
} else {
const index = selectmonth.findIndex(i => i == item);
selectmonth.splice(index, 1);
setSelectmonth([...selectmonth]);
}
console.log(selectmonth)
};
return (
<div className="box">
{province.map(item => {
return (
<span
key={item}
className={`item_span ${
selectmonth.length > 0 && selectmonth.includes(item)
? "item_span_choose"
: ""
}`}
onClick={() => btnclick(item)}
>
{item}
</span>
);
})}
</div>
);
}
export default A;
css文件
.box{
display: flex;
justify-content: flex-start;
align-items: center;
}
.item_span{
background-color: #ccc;
width: 50px;
height: 50px;
line-height: 50px;
margin-left: 10px;
}
.item_span_choose{
background-color: #4485fe;
}