React,在组件事件上呈现消息的最佳方法

React, Best method for rendering a message on a component event

本文关键字:消息 最佳 方法 组件 事件 React      更新时间:2023-09-26

新反应不太确定这里的最佳方法是什么。

我想做的是在另一个组件上运行事件时呈现一个组件(错误消息组件)。

这里的问题是我也应该能够呈现多个通知,每个通知都有不同的状态。(错误、警告、成功)。

附加信息,

我的主要应用程序类,

MainLayout = React.createClass({
  render() {
    return (
      <div>
        {this.props.header}
        {this.props.notification}
        {this.props.content}
        {this.props.footer}
      </div>
    )
  }
});

这是我的通知类,它呈现在 {this.props.notification}

SwiftNotification = React.createClass({
  getInitialState() {
    return {
      type: 'not-error',
    }
  },
  render() {
    return (
        <div className={ this.state.type + " jwlnotification container-fluid text-center"}>
          text for this....
        </div>
    )
  }
});

因此,在邀请成员功能上,我希望能够呈现通知组件,但在此组件之外。

BandEvent = React.createClass({
  propTypes: {
    id: React.PropTypes.string.isRequired,
    name: React.PropTypes.string.isRequired,
    location: React.PropTypes.string.isRequired
  },
  inviteMembers(e) {
    e.preventDefault();
    Meteor.call('inviteMembers', this.props.id, function(error, data) {
      if (error) {
        console.log(error.reason);
      } else {
        // what do we want to do here if we are successful..
        console.log(data);
      }
    });
  },
  render() {
    let { id, name, location } = this.props;
    return (
      <li className="bandEvent" ><button className="btn btn-info btn-sm" onClick={this.inviteMembers}> Invite Members </button> {name} at {location}</li>
    )
  }
});

谢谢!

您可以使用类似 flux 的实现(如 redux)将通知信息存储在单个对象中。然后,任何组件都可以使用您需要的元数据(messagemessage_type)发送通知。然后,通知组件将使用通知,并包含通知所需的所有业务逻辑:一次显示多少通知、如何显示它们、何时关闭它们等。

编辑:看起来这是一个你可以使用的包,或者至少源代码是我所描述的逻辑的一个例子。 https://github.com/indexiatech/re-notif

另一种变体如何组织消息组件并从外部运行其方法。

看看 Confirm.openModal 方法,任何 React 组件都可以调用它,而不管 Confirm 组件和调用组件之间的关系如何。此外,它在全局窗口中无需声明即可工作。

https://codesandbox.io/s/r7jop83wk4