组件如何在不将状态向上移动到组件树的情况下向其兄弟发送消息? [英] How can a component send a message to its sibling without moving the state up the component tree?

查看:102
本文介绍了组件如何在不将状态向上移动到组件树的情况下向其兄弟发送消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面"组件,其中包含一个表单和一个列表.表单和列表完全独立并且不相交,除了以下事实:保存表单时,列表应刷新.

I've got a "page" component which houses a form and a list. The form and the list are completely self-contained and disjoint except for the fact that when you save the form, the list should refresh.

我的页面组件整体上看起来像这样:

My page component looks like this, in its entirety:

export default class PaymentsPage extends React.PureComponent {

    static propTypes = {
        bookingId: XPropTypes.stringOrNumber.isRequired,
        test: PropTypes.bool,
        stripePublishableKey: PropTypes.string,
        stripeUserId: PropTypes.string,
    };

    render() {
        return (
            <div>
                <ContentSection title="Enter Payment" storageKey="record-payment">
                    <RecordPaymentForm bookingId={this.props.bookingId} test={this.props.test} />
                </ContentSection>
                <ContentSection title="Previous Payments" storageKey="previous-payments">
                    <PreviousPaymentsTable bookingId={this.props.bookingId} test={this.props.test} stripePublishableKey={this.props.stripePublishableKey} stripeUserId={this.props.stripeUserId} />
                </ContentSection>
            </div>
        )
    }
}

我的问题是,RecordPaymentForm如何发送消息到PreviousPaymentsTable以告诉它刷新?

My question is, how can RecordPaymentForm send a message to PreviousPaymentsTable to tell it to refresh?

我不想将RecordPaymentForm的状态上移到PaymentsPage,因为我希望它保持独立.

I don't want to move RecordPaymentForm's state up into PaymentsPage because I want it to remain self-contained.

我不使用助焊剂/氧化还原,也不打算立即对其进行计划.

I'm not using flux/redux, nor do I plan on it right now.

推荐答案

使用 mufa (面向事件的编程),兄弟姐妹之间的交流如下:

Using mufa (event oriented programming), communication among siblings will be as following :

import {fire} from 'mufa';

class RecordPaymentForm extends React.Component {

     // Assuming that the trigger to send the message is the following
     handleClick() {
       const message = 'this is a message from RecordPaymentForm';
       fire('sendSomething', message); 
     }
}

组件接收器(订户):

import {on} from 'mufa';

class PreviousPaymentsTable extends React.Component {

    componentDidMount() {
      on('sendSomething', (message) => {
         this.setState({recordPaymenetMessage: message});
      })
    }
}

//if your are using npm => import {on, fire} from 'mufa';
const {on, fire} = window.mufa; 

class RecordPaymentForm extends React.Component {


     onClick(event) {
       fire('addPayment', this.refs.item.value, this.refs.price.value); 
     }
     
     render() {
       return (
          <div>
            <input ref="item" placeholder="item name" /> 
            <input ref="price" placeholder="price" type="number" />
            <button onClick={this.onClick.bind(this)}>Add</button>
          </div>
          )
     }
}



class PreviousPaymentsTable extends React.Component {
  
    state={records:[]}
    componentDidMount() {
      on('addPayment', (item, price) => {
         this.setState({records: [...this.state.records, {item, price}]});
      })
    }

   
   render() {
    
      return (
        <ul>
          {
            this.state.records.map((r, index) => 
              <li key={index}> <b> {r.item} : </b> {r.price} $ </li>)
          }
        </ul>
      ) 
    }
}


class App extends React.Component {


  render() {
  
    return (
      <div>
         <RecordPaymentForm />
         <PreviousPaymentsTable />
      </div>
    )
  }
}

ReactDOM.render(<App />, document.querySelector('section'))

<script src="https://cdn.rawgit.com/abdennour/mufa/ddf78fd9/cdn/mufa-latest.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<section />

  1. publish (fire):在事件处理程序中被调用.

  1. publish (fire) : is called in events handlers.

subscribe (on):在componentDidMount中被调用.

unsubscribe (off):在componentWillUnmount

这篇关于组件如何在不将状态向上移动到组件树的情况下向其兄弟发送消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆