反应事件以删除警报消息?

时间:2019-09-15 16:16:23

标签: reactjs twitter-bootstrap events alert

Bootstrap具有这个不错的警报工具https://getbootstrap.com/docs/4.0/components/alerts/,我已经围绕Bootstrap Alert构建了我的React警报组件,例如(部分视图):

render() {
        return (
            <div>
              <div class={this.getAlertClasses()} style={this.getAlertStyle()} role="alert">
                {this.getMessage()}
              </div>
            </div>
        );
    }

我具有全局React状态,该状态由我的Alert组件使用以下命令读取:

const mapStateToProps = state => {
    return {
        orderCommandState: state.orderCommandState,
        orderCommandMessage: state.orderCommandMessage
    };
};

我的“订单”表单具有执行一些业务逻辑的操作/命令(搁置订单,运送,取消,保存,重新计算),并且作为我命令中的最后一个过程,还更新了state.orderCommandStatestate.orderCommandMessage。警报组件位于我的“订单”页面上,React自动将更新的状态变量传播到警报组件,警报组件显示状态和消息。很好。

我的问题是- React组件是否有一些合适的事件,在这些事件中,当不再有用时,我可以使Alert消息不可见-这意味着用户重新开始数据编辑时,例如当她单击某个可编辑字段时,或者单击某些按钮时,依此类推。什么是React事件,它可以捕获在执行一条命令后和显示警报之后发生的所有那些不同的用户交互事件?

1 个答案:

答案 0 :(得分:1)

您可以使用onBlur事件:

class YourContainer extends React.Component {
            constructor(){
                this.state = { showAlert: false }
                this.alertRef = React.createRef();
            }
            render(){
                { this.state.showAlert && // set to true when alert is needed
                    <div 
                      tabIndex="0"
                      className="your-alert-component" 
                      ref={this.alertRef}
                      onBlur={() => this.setState({showAlert: false})}
                    >
                       ..message
                    </div>
                }
            }
            componentDidUpdate()}{
                this.alertRef.current && this.alertRef.current.focus();
            }
        }