react实现点击时改变样式的方法:1、通过setState中的回调函数实现点击切换状态时所执行的功能;2、通过“

本教程操作环境:Windows10系统、react18.0.0版、Dell G3电脑。
react怎么实现点击时改变样式?
React点击/hover修改CSS样式
(1)点击修改样式
方法一:(typescript写法)
type state = {
selected: boolean;
};
class Measurement extends Component<{}, state> {
constructor(props:any) {
super(props);
this.state = { selected: false };
}
handleClick = (e:any) => {
this.setState({ selected: !this.state.selected }, () => {
if(!this.state.selected){
this.clearAll();
}
});
}
private rightBtnStyle: CSSProperties = {
background:"url(/assets/images/3.png) no-repeat center",
border: "none",
color: "white"
};
private rightBtnStyle2: CSSProperties = {
background:"url(/assets/images/1.png) no-repeat center",
border: "none",
color: "white"
};
//省略具体功能
render() {
var currentstyle;
if(this.state.selected){
currentstyle=this.rightBtnStyle2;
}
else{
currentstyle=this.rightBtnStyle;
}
return(
);
}
};PS: 此处点击切换状态时所执行的功能可以通过setState中的回调函数实现。
方法二:(动态添加className)
上述render换成如下
render() {
return (
);
}对应的css文件添加:
#Measurement {
.right-btn{
background:url(./images/3.png) no-repeat center;
border:none;
color: white;
width:100%;
height: 100%
}
.right-btn.active{
background:url(./images/1.png) no-repeat center;
}
}推荐学习:《react视频教程》










