简体   繁体   English

我如何在 React 中将事件从子组件发送到父组件?

[英]How do I emit events from a child component to a parent component in React?

I have a child component nested in a parent component.我有一个嵌套在父组件中的子组件。 I want the parent component to get notified whenever an event takes place in a child component.我希望父组件在子组件中发生事件时得到通知。 In Vue, I could do this:在 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" />

How can I achieve the same functionality in React?我怎样才能在 React 中实现相同的功能?

Some clarification: I want an event to be emitted to the parent component whenever I like eg, when an item has been added to a list, and not just when a button is clicked.一些说明:我希望每当我喜欢时将事件发送到父组件,例如,当一个项目被添加到列表中时,而不仅仅是单击按钮时。

One way you can achieve this is to give to the child component as props a function defined in the parent component.实现此目的的一种方法是将父组件中定义的函数作为 props 提供给子组件。

In parent:在父母:

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

At the child definition:在子定义中:

<Child notify_parent ={notify_me} />

In Child component:在子组件中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM