如何在React中从子组件发出事件到父组件?



我有一个嵌套在父组件中的子组件。我希望每当子组件中发生事件时,父组件都能得到通知。在Vue中,我可以这样做:

// inside the child component EventButton
// the event 'someEvent' gets emitted whenever the button is clicked
<button @click="$emit('someEvent')">
Emit event
</button>
// inside the parent component
<EventButton @someEvent="() => do something" />

如何在React中实现相同的功能?

澄清一下:我想让一个事件在我喜欢的时候被发送到父组件,例如,当一个项目被添加到列表中时,而不仅仅是当一个按钮被点击时。

实现这一点的一种方法是将父组件中定义的函数作为道具赋予子组件。

在父母:

function notify_me(){
#do what you want to do in the parent component using a state for example
}

子定义处:

<Child notify_parent ={notify_me} />

在子组件中:

<EventButton @someEvent={() => props.notify_me()}/>

最新更新