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.webp) no-repeat center", border: "none", color: "white" }; private rightBtnStyle2: CSSProperties = { background:"url(/assets/images/1.webp) 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.webp) no-repeat center; border:none; color: white; width:100 height: 100 } .right-btn.active{ background:url(./images/1.webp) no-repeat center; } }
更多相关技术文章,请访问HTML中文网!
以上就是react怎么更改css样式的详细内容,更多请关注易知道|edz.cc其它相关文章!