我如何在兄弟子组件上调用方法或在reactjs中向它发送事件?



所以我需要让兄弟姐妹子组件启动一个基于按钮单击的函数。我确信某种状态系统将是最好的,但这是一个单页原型ReactJS应用程序。我可以只是设置一些全局状态,然后有兄弟姐妹的孩子绑定到它?

代码的结构

<mainComponent>
<childOne>
<buttonOne />
<buttonTwo />
</childOne>
<childDose>
<SocialComponent>
<SubSocialComponent /> <--- This needs to now buttonOne and buttonTwo click.
</SocialComponent>
</childDose>
</mainComponent>

我想大多数人会告诉你,要么将状态提升到一个共同的祖先,然后向下传递道具,要么使用上下文API,要么使用像Redux这样的状态管理工具。

我在不同的地方使用所有这些,但用于特定类型的"事件"。我已经开始使用一种久经考验的Pub/Sub方法,这让我的应用变得更加灵活。我不确定这在React社区中有多流行,但我发现当组件可以出现在许多地方,而其他组件"关心"时,它非常有用。关于发生了什么

我使用eventemitter3,因为它似乎已经包含在我的大部分反应纱线。锁定文件。

我有什么相当于一个全局事件发射器对象(因为它必须是相同的对象)

import EventEmitter from 'eventemitter3'
window.App.eventEmitter = new EventEmitter()

任何组件都可以在任何时间发出事件:

emitChanged = () => {
window.App.eventEmitter.emit('payment-change')

任何组件都可以在任何时间监听任何其他事件。

componentDidMount = () => {
this.listen()
}
componentWillUnmount = () => {
this.stopListening()
}
listen = () => {
window.App.eventEmitter.on('credit-card-change', this.resource_manager.refresh )
window.App.eventEmitter.on('payment-change', this.resource_manager.refresh )
window.App.eventEmitter.on('handled-old-invoice-response', this.resource_manager.refresh )
}
stopListening = () => {
window.App.eventEmitter.off('credit-card-change', this.resource_manager.refresh )
window.App.eventEmitter.off('payment-change', this.resource_manager.refresh )
window.App.eventEmitter.off('handled-old-invoice-response', this.resource_manager.refresh )
}

最新更新