我试图在点击事件发生时显示带有过渡的背景颜色,并且没有进一步的交互,在 1 或 2 秒后淡出背景颜色。
基本上我想做的是active
属性在 css 中的作用,但是对于点击事件。
我目前的方法需要第二次触发点击事件以淡出背景颜色。我怎样才能一键完成
我的方法
handleClick(id) {
this.setState({
active: !this.state.active
})
}
<div className={this.state.active ? "txt_vote_bar_div txt_vote_bar_div_active" : "txt_vote_bar_div txt_vote_bar_div_notactive"}
onClick={this.handleClick()}>
</div>
我的 CSS
.txt_vote_bar_div {
width: 100%;
height: 50px;
min-height: 50px;
position: relative;
border: 1px solid #C6C6C6;
border-radius: 5px;
margin-bottom: 10px;
cursor: pointer;
}
.txt_vote_bar_div_active {
background-color: #001f3f;
transition: 1s ease-in-out;
}
.txt_vote_bar_div_notactive {
background-color: #FFFFFF;
transition: 1s ease-in-out;
}
在您的代码中,您犯了一个错误,即onClick={this.handleClick()}因此在每次渲染后触发您的点击事件。
这就是我所做的。
class Hello extends React.Component {
state = {
active: false
}
handleClick(e) {
this.setState({
active: !this.state.active
});
setTimeout(() => {
this.setState({
active: !this.state.active
});
}, 1000);
}
render() {
return (
<div className = { this.state.active ? "txt_vote_bar_div txt_vote_bar_div_active" : "txt_vote_bar_div txt_vote_bar_div_notactive" } onClick = { this.handleClick.bind(this) }></div>
);
}
}
ReactDOM.render( <
Hello initialName = "World" / > ,
document.getElementById('container')
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句