【问题标题】:React Redux Notification messageReact Redux 通知消息
【发布时间】:2017-04-02 04:48:04
【问题描述】:

我是 React Redux 的新手,我有一个显示消息的通知组件。我想在单击此关闭图标时隐藏此消息。 .这是我的代码。请建议。

export default class NotificationMessage extends Component {
    constructor(props) {
        super(props);
        this._onClick = this._onClick.bind(this);
    };
    _onClick() {
        console.log("close this button");

    };
    render() {
        var message;
        //let classerr = this.props.messageType ? 'notificationTheme.success' : 'notificationTheme.success';

        //let cssClasses = `${classerr}`;
        if(this.props.messageType=='success')
        {
            message = <div className={notificationTheme.success}>
                <span className={notificationTheme.message}>{this.props.content}</span>
                <i className={`${iconTheme['ic-remove']} ${notificationTheme.remove} ic-remove `} onClick={() => this._onClick()}/>

            </div>
        }
        else
        {
            message = <div className={notificationTheme.error}>
                <span className={notificationTheme.message}>{this.props.content}</span>
                <i className={`${iconTheme['ic-remove']} ${notificationTheme.remove} ic-remove `} onClick={() => this._onClick()}/>

            </div>
        }
        return (
            message
        )
    }
}

NotificationMessage.propTypes = {
    config: PropTypes.shape({
        content: PropTypes.string.isRequired
    })
};

【问题讨论】:

  • 你是在 Redux 中使用 React 还是单独使用 React?
  • 与 redux 反应,这是在每种形式中调用的单独组件。根据表单中的标记进行所有操作 - {this.state.displaySNotification ? : ''} {this.state.displayENotification ? : ''}
  • 您将无法在此组件中隐藏消息,除非您将消息更改为返回空 div,但我不建议这样做。该组件是否在另一个组件中呈现?如果是这样,我会使用状态来控制通知组件的呈现,并传入一个函数作为更新状态的道具。
  • 是的,这个组件通过我的代码在另一个组件中被调用,它在另一个组件的内部渲染方法方法中被调用,如下代码 - {this.state.displaySNotification ? : ''} {this.state.displayENotification ? : ''}
  • 如何通过将消息作为空 div 返回来做到这一点?

标签: reactjs notifications message


【解决方案1】:

您最初可以将反应状态 fDisplayNotification 设为 true

    constructor(props) {
      super(props);
      this.state = {fDisplayNotification : true}
      this._onClick = this._onClick.bind(this);
    };

按钮点击事件将状态设置为false

    _onClick() {
      this.setState({fDisplayNotification :false});
    }

这应该会在状态更改时触发组件的重新渲染。

如果 this.state.fDisplayNotification 为 false,则更改您的渲染方法以返回空。

【讨论】:

    【解决方案2】:

    从外部组件通过onClick函数。

    showMessage() {
       const { displayNotification } = this.state;
       this.setState({
          displayNotification: !displayNotification
       });
    }
    

    如果您基于状态显示通知,则只需通过 showMessage 函数作为 Notification 的道具,以在单击关闭图标时更改状态。然后当点击关闭图标时,它会将displayNotification更改为false并隐藏通知。

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 2017-02-23
      • 2019-04-28
      • 1970-01-01
      • 2017-03-15
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多