本教程操作環境: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( <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: 此處點擊切換狀態時所執行的功能可以通過setState中的回調函數實現。
方法二:(動態添加className)
上述render換成如下
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> ); }
對應的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視頻教程》
以上就是react怎么實現點擊時改變樣式的詳細內容,更多請關注php中文網其它相關文章!
關鍵詞: React