React implements the method of changing the style when clicking: 1. Through the callback function in setState to realize the function performed when clicking to switch the state; 2. Through "
The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.
How to change the style on click in react?
React click/hover to modify the CSS style
(1) Click to modify the style
Method 1: (typescript writing method)
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( <div className="tool-widget"> <Popover placement="left" content={this.content} trigger="click"> <Button className="right-btn" style={currentstyle} onClick={this.handleClick.bind(this)}></Button> </Popover> </div> ); } };
PS: The function performed when clicking here to switch states can be implemented through the callback function in setState.
Method 2: (Dynamicly add className)
The above render is replaced with the following
render() { return ( <div className="tool-widget" id="Measurement"> <Popover placement="left" content={this.content} trigger="click"> <Button className={["right-btn", this.state.selected ? "active":null].join(' ')} onClick={this.handleClick.bind(this)}></Button> </Popover> </div> ); }
The corresponding css file is added:
#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; } }
Recommended learning:《react video tutorial》
The above is the detailed content of How to change the style on click in react. For more information, please follow other related articles on the PHP Chinese website!