【问题标题】:Fade in and fade out transition using onClick使用 onClick 淡入淡出过渡
【发布时间】:2017-08-24 18:04:17
【问题描述】:

我试图在点击事件发生时显示带有过渡的背景颜色,并且在 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;
}

【问题讨论】:

  • 您正在调用处理程序,而不是传递 ref。这个onClick={this.handleClick()}应该改成这个onClick={this.handleClick}
  • @CraZyDroiD 请找到我的答案,如果您有任何问题,请告诉我。

标签: javascript css reactjs css-transitions


【解决方案1】:

Please find running example

在您的代码中犯了一个错误,即 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')
);

【讨论】:

    【解决方案2】:

    您可以通过设置超时将其改回来做到这一点。

    handleClick(id) {
    
            this.setState({
                active: !this.state.active
            });
    
            // The timeout will trigger after 1000ms. Use a fat arrow function
            // to keep the same reference to this.
            setTimeout(() => {
                this.setState({
                     active: false
                });
            }, 1000);
    }
    

    如果您不能使用粗箭头函数,您可以将this 分配给self 之类的变量,然后在超时处理程序中调用self.setState

    【讨论】:

      猜你喜欢
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      • 2013-11-03
      • 2018-12-07
      • 1970-01-01
      相关资源
      最近更新 更多